Java8 Tutorial PDF
Java8 Tutorial PDF
Java 8 is the most awaited and is a major feature release of Java programming
language.
This is an introductory tutorial that explains the basic-to-advanced features of
Java 8 and their usage in a simple and intuitive way.
Audience
This tutorial will be useful for most Java developers, starting from beginners to
experts.
After completing this tutorial, you will find yourself at a moderate level of expertise
in Java 8, from where you can take yourself to next levels.
Prerequisites
Knowledge of basic Java programming language is the only prerequisite for
learning the concepts explained in this tutorial.
Table of Contents
About the Tutorial ..................................................................................................................................... i
Audience .................................................................................................................................................... i
Prerequisites .............................................................................................................................................. i
Copyright & Disclaimer .............................................................................................................................. i
Table of Contents ...................................................................................................................................... ii
1. OVERVIEW ............................................................................................................................ 1
New Features ............................................................................................................................................ 1
3. LAMBDA EXPRESSIONS.......................................................................................................... 6
Syntax ....................................................................................................................................................... 6
Lambda Expressions Example ................................................................................................................... 6
Scope ........................................................................................................................................................ 8
ii
7. STREAMS............................................................................................................................. 23
What is Stream?...................................................................................................................................... 23
Generating Streams ................................................................................................................................ 24
forEach.................................................................................................................................................... 24
map ........................................................................................................................................................ 24
filter ........................................................................................................................................................ 24
limit ........................................................................................................................................................ 25
sorted ..................................................................................................................................................... 25
Parallel Processing .................................................................................................................................. 25
Collectors ................................................................................................................................................ 25
Statistics ................................................................................................................................................. 26
Stream Example ...................................................................................................................................... 26
iii
11. BASE64................................................................................................................................ 51
Nested Classes ........................................................................................................................................ 51
Methods ................................................................................................................................................. 51
Methods Inherited .................................................................................................................................. 52
iv
1. OVERVIEW
Java 8
New Features
New tools - New compiler tools and utilities are added like jdeps to figure
out dependencies.
Java 8
names1.add("Naresh ");
names1.add("Kalpesh ");
Java 8
s1.compareTo(s2));
}
}
Run the program to get the following result.
Sort using Java 7 syntax:
[ Kalpesh Mahesh Naresh Ramesh Suresh ]
Sort using Java 8 syntax:
[ Kalpesh Mahesh Naresh Ramesh Suresh ]
Here the sortUsingJava8() method uses sort function with a lambda expression
as parameter to get the sorting criteria.
2. ENVIRONMENT SETUP
Java 8
using
our
online
compiler
available
at
Java 8
Edit the 'C:\autoexec.bat' file and add the following line at the end:
'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
Notepad: On Windows machine, you can use any simple text editor like
Notepad (recommended for this tutorial) or TextPad.
3. LAMBDA EXPRESSIONS
Java 8
Lambda expressions are introduced in Java 8 and are touted to be the biggest
feature of Java 8. Lambda expression facilitates functional programming, and
simplifies the development a lot.
Syntax
A lambda expression is characterized by the following syntax.
parameter -> expression body
Following are the important characteristics of a lambda expression.
Java8Tester.java
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
Java 8
//with parenthesis
GreetingService greetService1 = message ->
System.out.println("Hello " + message);
//without parenthesis
GreetingService greetService2 = (message) ->
System.out.println("Hello " + message);
greetService1.sayMessage("Mahesh");
greetService2.sayMessage("Suresh");
}
interface MathOperation {
int operation(int a, int b);
}
interface GreetingService {
void sayMessage(String message);
}
7
Java 8
Scope
Using lambda expression, you can refer to any final variable or effectively final
variable (which is assigned only once). Lambda expression throws a compilation
error, if a variable is assigned a value the second time.
Java 8
Scope Example
Create the following Java program using any editor of your choice in, say, C:\>
JAVA.
Java8Tester.java
public class Java8Tester {
final static String salutation = "Hello! ";
public static void main(String args[]){
GreetingService greetService1 = message ->
System.out.println(salutation + message);
greetService1.sayMessage("Mahesh");
}
interface GreetingService {
void sayMessage(String message);
}
}
4. METHOD REFERENCES
Java 8
Static methods
Instance methods
Java8Tester.java
import java.util.List;
import java.util.ArrayList;
public class Java8Tester {
names.forEach(System.out::println);
}
}
10
Java 8
11
Java 8
5. FUNCTIONAL INTERFACES
BiConsumer<T,U>
Represents an operation that accepts two input arguments, and returns
no result.
BiFunction<T,U,R>
Represents a function that accepts two arguments and produces a result.
BinaryOperator<T>
Represents an operation upon two operands of the same type, producing
a result of the same type as the operands.
BiPredicate<T,U>
Represents a predicate (Boolean-valued function) of two arguments.
BooleanSupplier
Represents a supplier of Boolean-valued results.
Consumer<T>
Represents an operation that accepts a single input argument and
returns no result.
DoubleBinaryOperator
Represents an operation upon two double-valued operands and
producing a double-valued result.
DoubleConsumer
Represents an operation that accepts a single double-valued argument
and returns no result.
DoubleFunction<R>
Represents a function that accepts a double-valued argument and
produces a result.
12
Java 8
10
DoublePredicate
Represents a predicate (Boolean-valued function) of one double-valued
argument.
11
DoubleSupplier
Represents a supplier of double-valued results.
12
DoubleToIntFunction
Represents a function that accepts a double-valued argument and
produces an int-valued result.
13
DoubleToLongFunction
Represents a function that accepts a double-valued argument and
produces a long-valued result.
14
DoubleUnaryOperator
Represents an operation on a single double-valued operand that
produces a double-valued result.
15
Function<T,R>
Represents a function that accepts one argument and produces a result.
16
IntBinaryOperator
Represents an operation upon two int-valued operands and produces an
int-valued result.
17
IntConsumer
Represents an operation that accepts a single int-valued argument and
returns no result.
18
IntFunction<R>
Represents a function that accepts an int-valued argument and produces
a result.
19
IntPredicate
Represents a predicate (Boolean-valued function) of one int-valued
argument.
20
IntSupplier
Represents a supplier of int-valued results.
21
IntToDoubleFunction
Represents a function that accepts an int-valued argument and produces
a double-valued result.
13
Java 8
22
IntToLongFunction
Represents a function that accepts an int-valued argument and produces
a long-valued result.
23
IntUnaryOperator
Represents an operation on a single int-valued operand that produces an
int-valued result.
24
LongBinaryOperator
Represents an operation upon two long-valued operands and produces a
long-valued result.
25
LongConsumer
Represents an operation that accepts a single long-valued argument and
returns no result.
26
LongFunction<R>
Represents a function that accepts a long-valued argument and produces
a result.
27
LongPredicate
Represents a predicate (Boolean-valued function) of one long-valued
argument.
28
LongSupplier
Represents a supplier of long-valued results.
29
LongToDoubleFunction
Represents a function that accepts a long-valued argument and produces
a double-valued result.
30
LongToIntFunction
Represents a function that accepts a long-valued argument and produces
an int-valued result.
31
LongUnaryOperator
Represents an operation on a single long-valued operand that produces
a long-valued result.
32
ObjDoubleConsumer<T>
Represents an operation that accepts an object-valued and a doublevalued argument, and returns no result.
14
Java 8
33
ObjIntConsumer<T>
Represents an operation that accepts an object-valued and an int-valued
argument, and returns no result.
34
ObjLongConsumer<T>
Represents an operation that accepts an object-valued and a long-valued
argument, and returns no result.
35
Predicate<T>
Represents a predicate (Boolean-valued function) of one argument.
36
Supplier<T>
Represents a supplier of results.
37
ToDoubleBiFunction<T,U>
Represents a function that accepts two arguments and produces a
double-valued result.
38
ToDoubleFunction<T>
Represents a function that produces a double-valued result.
39
ToIntBiFunction<T,U>
Represents a function that accepts two arguments and produces an intvalued result.
40
ToIntFunction<T>
Represents a function that produces an int-valued result.
41
ToLongBiFunction<T,U>
Represents a function that accepts two arguments and produces a longvalued result.
42
ToLongFunction<T>
Represents a function that produces a long-valued result.
43
UnaryOperator<T>
Represents an operation on a single operand that produces a result of
the same type as its operand.
Java 8
Create the following Java program using any editor of your choice in, say, C:\>
JAVA.
Java8Tester.java
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
16
Java 8
for(Integer n: list)
if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}
}
Here we've passed Predicate interface, which takes a single input and returns
Boolean.
Java 8
4
5
6
7
8
9
18
6. DEFAULT METHODS
Java 8
Syntax
public interface vehicle {
default void print(){
System.out.println("I am a vehicle!");
}
}
Multiple Defaults
With default functions in interfaces, there is a possibility that a class is
implementing two interfaces with same default methods. The following code
explains how this ambiguity can be resolved.
public interface vehicle {
default void print(){
System.out.println("I am a vehicle!");
}
}
public interface fourWheeler {
default void print(){
System.out.println("I am a four wheeler!");
}
}
19
Java 8
First solution is
implementation.
that overrides
the
default
Java8Tester.java
public class Java8Tester {
public static void main(String args[]){
20
Java 8
interface Vehicle {
default void print(){
System.out.println("I am a vehicle!");
}
static void blowHorn(){
System.out.println("Blowing horn!!!");
}
}
interface FourWheeler {
default void print(){
System.out.println("I am a four wheeler!");
}
}
Java 8
C:\JAVA>java Java8Tester
It should produce the following output:
I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!
22
7. STREAMS
Java 8
Stream is a new abstract layer introduced in Java 8. Using stream, you can process
data in a declarative way similar to SQL statements. For example, consider the
following SQL statement.
SELECT max(salary),employee_id,employee_name FROM Employee
The above SQL expression automatically returns the maximum salaried
employee's details, without doing any computation on the developer's end. Using
collections framework in Java, a developer has to use loops and make repeated
checks. Another concern is efficiency; as multi-core processors are available at
ease, a Java developer has to write parallel code processing that can be pretty
error-prone.
To resolve such issues, Java 8 introduced the concept of stream that lets the
developer to process data declaratively and leverage multicore architecture
without the need to write any specific code for it.
What is Stream?
Stream represents a sequence of objects from a source, which supports aggregate
operations. Following are the characteristics of a Stream:
Pipelining - Most of the stream operations return stream itself so that their
result can be pipelined. These operations are called intermediate operations
and their function is to take input, process them, and return output to the
target. collect() method is a terminal operation which is normally present
at the end of the pipelining operation to mark the end of the stream.
23
Java 8
Generating Streams
With Java 8, Collection interface has two methods to generate a Stream.
forEach
Stream has provided a new method forEach to iterate each element of the
stream. The following code segment shows how to print 10 random numbers using
forEach.
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
map
The map method is used to map each element to its corresponding result. The
following code segment prints unique squares of numbers using map.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
//get list of unique squares
List<Integer> squaresList = numbers.stream().map( i ->
i*i).distinct().collect(Collectors.toList());
filter
The filter method is used to eliminate elements based on a criteria. The following
code segment prints a count of empty strings using filter.
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
24
Java 8
limit
The limit method is used to reduce the size of the stream. The following code
segment shows how to print 10 random numbers using limit.
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
sorted
The sorted method is used to sort the stream. The following code segment shows
how to print 10 random numbers in a sorted order.
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
Parallel Processing
parallelStream is the alternative of stream for parallel processing. Take a look at
the following code segment that prints a count of empty strings using
parallelStream.
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
Collectors
Collectors are used to combine the result of processing on the elements of a
stream. Collectors can be used to return a list or a string.
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
Java 8
Statistics
With Java 8, statistics collectors are introduced to calculate all statistics when
stream processing is being done.
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
Stream Example
Create the following Java program using any editor of your choice in, say, C:\>
JAVA.
Java8Tester.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.Map;
Java 8
"abcd","", "jkl");
System.out.println("List: " +strings);
long count = getCountEmptyStringUsingJava7(strings);
System.out.println("Empty Strings: " + count);
count = getCountLength3UsingJava7(strings);
System.out.println("Strings of length 3: " + count);
deleteEmptyStringsUsingJava7(strings);
getSquares(numbers);
Java 8
System.out.println(random.nextInt());
}
System.out.println("Using Java 8: ");
System.out.println("List: " +strings);
count = strings.stream().filter(string->string.isEmpty()).count();
System.out.println("Empty Strings: " + count);
Java 8
//parallel processing
count = strings.parallelStream().filter(string ->
string.isEmpty()).count();
System.out.println("Empty Strings: " + count);
}
{
int count = 0;
for(String string: strings){
if(string.isEmpty()){
count++;
}
}
return count;
}
private static int getCountLength3UsingJava7(List<String> strings){
int count = 0;
for(String string: strings){
if(string.length() == 3){
count++;
}
}
return count;
}
private static List<String> deleteEmptyStringsUsingJava7(List<String>
strings){
List<String> filteredList = new ArrayList<String>();
for(String string: strings){
if(!string.isEmpty()){
filteredList.add(string);
}
}
29
Java 8
return filteredList;
}
mergedString.substring(0, mergedString.length()-2);
if(!squaresList.contains(square)){
squaresList.add(square);
}
}
return squaresList;
}
Java 8
}
return max;
}
Java 8
C:\JAVA>java Java8Tester
It should produce the following result:
Using Java 7:
List: [abc, , bc, efg, abcd, , jkl]
Empty Strings: 2
Strings of length 3: 3
Filtered List: [abc, bc, efg, abcd, jkl]
Merged String: abc, bc, efg, abcd, jkl
Squares List: [9, 4, 49, 25]
List: [1, 2, 13, 4, 15, 6, 17, 8, 19]
Highest number in List : 19
Lowest number in List : 1
Sum of all numbers : 85
Average of all numbers : 9
Random Numbers:
-1279735475
903418352
-1133928044
-1571118911
628530462
18407523
-881538250
-718932165
270259229
421676854
Using Java 8:
List: [abc, , bc, efg, abcd, , jkl]
Empty Strings: 2
Strings of length 3: 3
Filtered List: [abc, bc, efg, abcd, jkl]
Merged String: abc, bc, efg, abcd, jkl
Squares List: [9, 4, 49, 25]
List: [1, 2, 13, 4, 15, 6, 17, 8, 19]
32
Java 8
number in List : 1
numbers : 9.444444444444445
Random Numbers:
-1009474951
-551240647
-2484714
181614550
933444268
1227850416
1579250773
1627454872
1683033687
1798939493
Empty Strings: 2
33
8. OPTIONAL CLASS
Java 8
Class Declaration
Following is the declaration for java.util.Optional<T> class:
public final class Optional<T>
extends Object
Class Methods
S. No.
T get()
If a value is present in this Optional, returns the value, otherwise
throws NoSuchElementException.
34
Java 8
int hashCode()
Returns the hash code value of the present value, if any, or 0 (zero) if
no value is present.
boolean isPresent()
Returns true if there is a value present, otherwise false.
10
11
12
T orElse(T other)
Returns the value if present, otherwise returns other.
13
14
15
String toString()
Returns a non-empty string representation of this Optional suitable for
debugging.
java.lang.Object
35
Java 8
Optional Example
Create the following Java program using any editor of your choice in, say, C:\>
JAVA.
Java8Tester.java
import java.util.Optional;
Integer value1 =
null;
Integer value2 =
new Integer(10);
Optional<Integer> b = Optional.of(value2);
System.out.println(java8Tester.sum(a,b));
}
36
Java 8
37
Java 8
jjs
For Nashorn engine, JAVA 8 introduces a new command line tool, jjs, to execute
javascript codes at console.
Interpreting js File
Create and save the file sample.js in c:\> JAVA folder.
sample.js
print('Hello World!');
Open console and use the following command.
C:\JAVA>jjs sample.js
It will produce the following output:
Hello World!
38
Java 8
Pass Arguments
Open the console and use the following command.
C:\JAVA> jjs -- a b c
jjs> print('letters: ' +arguments.join(", "))
letters: a, b, c
jjs>
Example
Create the following Java program using any editor of your choice in, say, C:\>
JAVA.
Java8Tester.java
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
Java 8
sample.js
var BigDecimal = Java.type('java.math.BigDecimal');
Java 8
With Java 8, a new Date-Time API is introduced to cover the following drawbacks
of old date-time API.
Not thread safe - java.util.Date is not thread safe, thus developers have
to deal with concurrency issue while using date. The new date-time API is
immutable and does not have setter methods.
Poor design - Default Date starts from 1900, month starts from 1, and day
starts from 0, so no uniformity. The old API had less direct methods for
date operations. The new API provides numerous utility methods for such
operations.
Java 8 introduces a new date-time API under the package java.time. Following are
some of the important classes introduced in java.time package.
Java8Tester.java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
Java 8
java8tester.testLocalDateTime();
}
LocalDateTime date2 =
currentTime.withDayOfMonth(10).withYear(2012);
System.out.println("date2: " + date2);
//parse a string
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
42
Java 8
}
}
Java8Tester.java
import java.time.ZonedDateTime;
import java.time.ZoneId;
Java 8
Java8Tester.java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
44
Java 8
Java 8
Java8Tester.java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.time.Duration;
import java.time.Period;
Java 8
Java 8
Temporal Adjusters
TemporalAdjuster is used to perform the date mathematics. For example, get the
"Second Saturday of the Month" or "Next Tuesday". Let us see them in action.
Create the following Java program using any editor of your choice in, say, C:\>
JAVA.
Java8Tester.java
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
Java 8
Backward Compatibility
A toInstant() method is added to the original Date and Calendar objects, which
can be used to convert them to the new Date-Time API. Use an
ofInstant(Insant,ZoneId) method to get a LocalDateTime or ZonedDateTime
object. Let us see them in action.
Create the following Java program using any editor of your choice in, say, C:\>
JAVA.
Java8Tester.java
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.time.Instant;
import java.time.ZoneId;
Java 8
java8tester.testBackwardCompatability();
}
50
11. BASE64
Java 8
With Java 8, Base64 has finally got its due. Java 8 now has inbuilt encoder and
decoder for Base64 encoding. In Java 8, we can use three types of Base64
encoding.
Nested Classes
S. No.
Methods
S. No.
51
Java 8
Methods Inherited
This class inherits methods from the following class:
java.lang.Object
Base64 Example
Create the following Java program using any editor of your choice in say C:/>
JAVA.
Java8Tester.java
import java.util.Base64;
import java.util.UUID;
import java.io.UnsupportedEncodingException;
Java 8
// Decode
byte[] base64decodedBytes =
Base64.getDecoder().decode(base64encodedString);
System.out.println("Original String: "+new
String(base64decodedBytes, "utf-8"));
base64encodedString =
Base64.getUrlEncoder().encodeToString("TutorialsPoint?java8"
.getBytes("utf-8"));
}catch(UnsupportedEncodingException e){
System.out.println("Error :"+e.getMessage());
}
}
53
Java 8
54