Java8 Tutorial
Java8 Tutorial
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.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Syntax ..................................................................................................................................................... 5
Scope ...................................................................................................................................................... 7
ii
7. JAVA 8 ─ STREAMS............................................................................................................. 20
forEach .................................................................................................................................................. 21
map ....................................................................................................................................................... 21
filter ...................................................................................................................................................... 21
limit....................................................................................................................................................... 21
sorted.................................................................................................................................................... 22
Collectors .............................................................................................................................................. 22
Statistics ................................................................................................................................................ 22
jjs .......................................................................................................................................................... 33
iii
Temporal Adjusters ............................................................................................................................... 42
Methods................................................................................................................................................ 45
iv
Java 8
1. Java 8 ─ Overview
JAVA 8 is a major feature release of JAVA programming language development. Its initial
version was released on 18 March 2014. With the Java 8 release, Java provided supports
for functional programming, new JavaScript engine, new APIs for date time manipulation,
new streaming API, etc.
New Features
Lambda expression - Adds functional processing capability to Java.
New tools - New compiler tools and utilities are added like ‘jdeps’ to figure out
dependencies.
Stream API - New stream API to facilitate pipeline processing.
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
1
Java 8
names2.add("Suresh ");
names2.add("Ramesh ");
names2.add("Naresh ");
names2.add("Kalpesh ");
Here the sortUsingJava8() method uses sort function with a lambda expression as
parameter to get the sorting criteria.
2
Java 8
2. Java 8 ─ Environment Setup
For most of the examples given in this tutorial, you will find a Try it option in our website
code sections at the top right corner that will take you to the online compiler. So just make
use of it and enjoy your learning.
Follow the instructions to download Java, and run the .exe to install Java on your machine.
Once you have installed Java on your machine, you would need to set environment
variables to point to correct installation directories.
3. Now, alter the 'Path' variable so that it also contains the path to the Java
executable. For example, if the path is currently set to
'C:\WINDOWS\SYSTEM32', then change your path to read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
3
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'
For example, if you use bash as your shell, then you would add the following line at the
end of your '.bashrc: export PATH=/path/to/java:$PATH'
Notepad: On Windows machine, you can use any simple text editor like Notepad
(recommended for this tutorial) or TextPad.
Eclipse: It is also a Java IDE developed by the Eclipse open-source community and
can be downloaded from http://www.eclipse.org/.
4
Java 8
3. Java 8 ─ Lambda Expressions
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.
Optional curly braces - No need to use curly braces in expression body if the
body contains a single statement.
Optional return keyword – The compiler automatically returns the value if the
body has a single expression to return the value. Curly braces are required to
indicate that expression returns a value.
Java8Tester.java
public class Java8Tester {
public static void main(String args[]){
Java8Tester tester = new Java8Tester();
//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);
}
C:\JAVA>javac Java8Tester.java
6
Java 8
C:\JAVA>java Java8Tester
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
Lambda expression eliminates the need of anonymous class and gives a very simple
yet powerful functional programming capability to Java.
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.
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);
}
}
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
Hello! Mahesh
8
Java 8
4. Java 8 ─ Method References
Static methods
Instance methods
Java8Tester.java
import java.util.List;
import java.util.ArrayList;
public class Java8Tester {
names.forEach(System.out::println);
}
}
C:\JAVA>javac Java8Tester.java
9
Java 8
C:\JAVA>java Java8Tester
Mahesh
Suresh
Ramesh
Naresh
Kalpesh
10
Java 8
5. Java 8 ─ Functional Interfaces
BiConsumer<T,U>
1 Represents an operation that accepts two input arguments, and returns no
result.
BiFunction<T,U,R>
2
Represents a function that accepts two arguments and produces a result.
BinaryOperator<T>
3 Represents an operation upon two operands of the same type, producing a
result of the same type as the operands.
BiPredicate<T,U>
4
Represents a predicate (Boolean-valued function) of two arguments.
BooleanSupplier
5
Represents a supplier of Boolean-valued results.
Consumer<T>
6 Represents an operation that accepts a single input argument and returns no
result.
DoubleBinaryOperator
7 Represents an operation upon two double-valued operands and producing a
double-valued result.
DoubleConsumer
8 Represents an operation that accepts a single double-valued argument and
returns no result.
DoubleFunction<R>
9 Represents a function that accepts a double-valued argument and produces a
result.
DoublePredicate
10 Represents a predicate (Boolean-valued function) of one double-valued
argument.
11
Java 8
DoubleSupplier
11
Represents a supplier of double-valued results.
DoubleToIntFunction
12 Represents a function that accepts a double-valued argument and produces an
int-valued result.
DoubleToLongFunction
13 Represents a function that accepts a double-valued argument and produces a
long-valued result.
DoubleUnaryOperator
14 Represents an operation on a single double-valued operand that produces a
double-valued result.
Function<T,R>
15
Represents a function that accepts one argument and produces a result.
IntBinaryOperator
16 Represents an operation upon two int-valued operands and produces an int-
valued result.
IntConsumer
17 Represents an operation that accepts a single int-valued argument and returns
no result.
IntFunction<R>
18 Represents a function that accepts an int-valued argument and produces a
result.
IntPredicate
19
Represents a predicate (Boolean-valued function) of one int-valued argument.
IntSupplier
20
Represents a supplier of int-valued results.
IntToDoubleFunction
21 Represents a function that accepts an int-valued argument and produces a
double-valued result.
IntToLongFunction
22 Represents a function that accepts an int-valued argument and produces a long-
valued result.
IntUnaryOperator
23 Represents an operation on a single int-valued operand that produces an int-
valued result.
12
Java 8
LongBinaryOperator
24 Represents an operation upon two long-valued operands and produces a long-
valued result.
LongConsumer
25 Represents an operation that accepts a single long-valued argument and returns
no result.
LongFunction<R>
26 Represents a function that accepts a long-valued argument and produces a
result.
LongPredicate
27
Represents a predicate (Boolean-valued function) of one long-valued argument.
LongSupplier
28
Represents a supplier of long-valued results.
LongToDoubleFunction
29 Represents a function that accepts a long-valued argument and produces a
double-valued result.
LongToIntFunction
30 Represents a function that accepts a long-valued argument and produces an
int-valued result.
LongUnaryOperator
31 Represents an operation on a single long-valued operand that produces a long-
valued result.
ObjDoubleConsumer<T>
32 Represents an operation that accepts an object-valued and a double-valued
argument, and returns no result.
ObjIntConsumer<T>
33 Represents an operation that accepts an object-valued and an int-valued
argument, and returns no result.
ObjLongConsumer<T>
34 Represents an operation that accepts an object-valued and a long-valued
argument, and returns no result.
Predicate<T>
35
Represents a predicate (Boolean-valued function) of one argument.
Supplier<T>
36
Represents a supplier of results.
13
Java 8
ToDoubleBiFunction<T,U>
37 Represents a function that accepts two arguments and produces a double-
valued result.
ToDoubleFunction<T>
38
Represents a function that produces a double-valued result.
ToIntBiFunction<T,U>
39 Represents a function that accepts two arguments and produces an int-valued
result.
ToIntFunction<T>
40
Represents a function that produces an int-valued result.
ToLongBiFunction<T,U>
41 Represents a function that accepts two arguments and produces a long-valued
result.
ToLongFunction<T>
42
Represents a function that produces a long-valued result.
UnaryOperator<T>
43 Represents an operation on a single operand that produces a result of the same
type as its operand.
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;
Here we've passed Predicate interface, which takes a single input and returns Boolean.
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
15
Java 8
16
Java 8
6. Java 8 ─ Default Methods
For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration.
Thus, adding such method will simply break the collection framework implementations.
Java 8 introduces default method so that List/Collection interface can have a default
implementation of forEach method, and the class implementing these interfaces need not
implement the same.
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.
17
Java 8
First solution is to create an own method that overrides the default implementation.
Second solution is to call the default method of the specified interface using super.
Java8Tester.java
public class Java8Tester {
public static void main(String args[]){
Vehicle vehicle = new Car();
vehicle.print();
}
}
interface Vehicle {
18
Java 8
interface FourWheeler {
default void print(){
System.out.println("I am a four wheeler!");
}
}
class Car implements Vehicle, FourWheeler {
public void print(){
Vehicle.super.print();
FourWheeler.super.print();
Vehicle.blowHorn();
System.out.println("I am a car!");
}
}
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!
19
Java 8
7. Java 8 ─ Streams
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.
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.
Generating Streams
With Java 8, Collection interface has two methods to generate a Stream.
20
Java 8
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.
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.
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.
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.
21
Java 8
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.
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.
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.
Statistics
With Java 8, statistics collectors are introduced to calculate all statistics when stream
processing is being done.
22
Java 8
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;
count = getCountLength3UsingJava7(strings);
System.out.println("Strings of length 3: " + count);
23
Java 8
24
Java 8
//parallel processing
count = strings.parallelStream().filter(string ->
string.isEmpty()).count();
System.out.println("Empty Strings: " + 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);
}
}
return filteredList;
}
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
27
Java 8
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]
Highest number in List : 19
Lowest number in List : 1
Sum of all numbers : 85
Average of all numbers : 9.444444444444445
Random Numbers:
28
Java 8
-1009474951
-551240647
-2484714
181614550
933444268
1227850416
1579250773
1627454872
1683033687
1798939493
Empty Strings: 2
29
Java 8
8. Java 8 ─ Optional Class
Optional is a container object used to contain not-null objects. Optional object is used to
represent null with absent value. This class has various utility methods to facilitate code
to handle values as ‘available’ or ‘not available’ instead of checking null values. It is
introduced in Java 8 and is similar to what Optional is in Guava.
Class Declaration
Following is the declaration for java.util.Optional<T> class:
Class Methods
S. No. Method & Description
T get()
5 If a value is present in this Optional, returns the value, otherwise throws
NoSuchElementException.
int hashCode()
6 Returns the hash code value of the present value, if any, or 0 (zero) if no
value is present.
30
Java 8
boolean isPresent()
8
Returns true if there is a value present, otherwise false.
T orElse(T other)
12
Returns the value if present, otherwise returns other.
String toString()
15 Returns a non-empty string representation of this Optional suitable for
debugging.
java.lang.Object
Optional Example
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
import java.util.Optional;
31
Java 8
System.out.println(java8Tester.sum(a,b));
}
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
With Java 8, Nashorn, a much improved javascript engine is introduced, to replace the
existing Rhino. Nashorn provides 2 to 10 times better performance, as it directly compiles
the code in memory and passes the bytecode to JVM. Nashorn uses invoke dynamics
feature, introduced in Java 7 to improve performance.
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!');
C:\JAVA>jjs sample.js
Hello World!
C:\JAVA>jjs
jjs> print("Hello, World!")
Hello, World!
jjs> quit()
>>
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>
33
Java 8
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;
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
Mahesh
12
34
Java 8
sample.js
var BigDecimal = Java.type('java.math.BigDecimal');
C:\JAVA>jjs sample.js
78952000000000000003.20
35
Java 8
10. Java 8 ─ New Date-Time API
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.
Difficult time zone handling - Developers had to write a lot of code to deal with
timezone issues. The new API has been developed keeping domain-specific design
in mind.
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.
Create the following java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
36
Java 8
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);
}
}
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
37
Java 8
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
import java.time.ZonedDateTime;
import java.time.ZoneId;
38
Java 8
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
date1: 2007-12-03T10:15:30+05:00[Asia/Karachi]
ZoneId: Europe/Paris
CurrentZone: Etc/UTC
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.ChronoUnit;
39
Java 8
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
Java8Tester.java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.time.Duration;
40
Java 8
import java.time.Period;
C:\JAVA>javac Java8Tester.java
41
Java 8
C:\JAVA>java Java8Tester
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;
42
Java 8
LocalDate.of(date1.getYear(),date1.getMonth(), 1);
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
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;
43
Java 8
java8tester.testBackwardCompatability();
}
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
44
Java 8
11. Java 8 ─ Base64
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. Nested class and Description
Methods
S. No. Method Name and Description
45
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;
// Decode
46
Java 8
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"));
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
47
Java 8
48