Java 8 Features
Oracle released a new version of Java as Java 8 in March 18, 2014. It
was a revolutionary release of the Java for software development
platform. It includes various upgrades to the Java programming, JVM,
Tools and libraries.
ava 8 Programming Language Enhancements
Java 8 provides following features for Java Programming:
o Lambda expressions,
o Method references,
o Functional interfaces,
o Stream API,
o Default methods,
o Base64 Encode Decode,
o Static methods in interface,
o Optional class,
o Collectors class,
o ForEach() method,
o Nashorn JavaScript Engine,
o Parallel Array Sorting,
o Type and Repating Annotations,
o IO Enhancements,
o Concurrency Enhancements,
o JDBC Enhancements etc.
Lambda Expressions
Lambda expression helps us to write our code in functional style. It
provides a clear and concise way to implement SAM interface(Single
Abstract Method) by using an expression. It is very useful in collection
library in which it helps to iterate, filter and extract data.
Functional Interface
Lambda expression provides implementation of functional interface. An
interface which has only one abstract method is called functional
interface. Java provides an anotation @FunctionalInterface, which is
used to declare an interface as functional interface.
Java Default Methods
Java provides a facility to create default methods inside the interface.
Methods which are defined inside the interface and tagged with default
are known as default methods. These methods are non-abstract methods.
Java Default Method Example
1. interface Sayable{
2. // Default method
3. default void say(){
4. System.out.println("Hello, this is default method");
5. }
6. // Abstract method
7. void sayMore(String msg);
8. }
9. public class DefaultMethods implements Sayable{
10. public void sayMore(String msg){ // implementing abstract m
ethod
11. System.out.println(msg);
12. }
13. public static void main(String[] args) {
14. DefaultMethods dm = new DefaultMethods();
15. dm.say(); // calling default method
16. dm.sayMore("Work is worship"); // calling abstract method
17.
18. }
19. }
Static Methods inside Java 8 Interface
You can also define static methods inside the interface. Static methods
are used to define utility methods. The following example explain, how
to implement static method in interface?
1. interface Sayable{
2. // default method
3. default void say(){
4. System.out.println("Hello, this is default method");
5. }
6. // Abstract method
7. void sayMore(String msg);
8. // static method
9. static void sayLouder(String msg){
10. System.out.println(msg);
11. }
12. }
13. public class DefaultMethods implements Sayable{
14. public void sayMore(String msg){ // implementing abstract met
hod
15. System.out.println(msg);
16. }
17. public static void main(String[] args) {
18. DefaultMethods dm = new DefaultMethods();
19. dm.say(); // calling default method
20. dm.sayMore("Work is worship"); // calling abstract method
21. Sayable.sayLouder("Helloooo..."); // calling static method
22. }
23. }
Why use Lambda Expression
1. To provide the implementation of Functional interface.
2. Less coding.
Java Lambda Expression Syntax
1. (argument-list) -> {body}
2. ava lambda expression is consisted of three components.
3. 1) Argument-list: It can be empty or non-empty as well.
4. 2) Arrow-token: It is used to link arguments-list and body of
expression.
5. 3) Body: It contains expressions and statements for lambda
expression.
6. No Parameter Syntax
7. () -> {
8. //Body of no parameter lambda
9. }
One Parameter Syntax
1. (p1) -> {
2. //Body of single parameter lambda
3. }
Two Parameter Syntax
1. (p1,p2) -> {
2. //Body of multiple parameter lambda
3. }
Let's see a scenario where we are not implementing Java lambda
expression. Here, we are implementing an interface without using
lambda expression.
Without Lambda Expression
interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;
//without lambda, Drawable implementation using anonymous class
Drawable d=new Drawable(){
public void draw(){System.out.println("Drawing "+width);}
};
d.draw();
}
}
Java Lambda Expression Example
@FunctionalInterface //It is optional
interface Drawable{
public void draw();
}
public class LambdaExpressionExample2 {
public static void main(String[] args) {
int width=10;
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}
forEach
Java provides a new method forEach() to iterate the elements. It is
defined in Iterable and Stream interfaces
It is a default method defined in the Iterable interface. Collection classes
which extends Iterable interface can use forEach() method to iterate
elements.
This method takes a single parameter which is a functional interface. So,
you can pass lambda expression as an argument.
forEach() Signature in Iterable Interface
default void forEach(Consumer<super T>action)
1. import java.util.ArrayList;
2. import java.util.List;
3. public class ForEachExample {
4. public static void main(String[] args) {
5. List<String> gamesList = new ArrayList<String>();
6. gamesList.add("Football");
7. gamesList.add("Cricket");
8. gamesList.add("Chess");
9. gamesList.add("Hocky");
10. System.out.println("------------Iterating by passing lambda
expression--------------");
11. gamesList.forEach(games -> System.out.println(games));
12.
13. }
14. }
Java 8 forEach() example 2
1. import java.util.ArrayList;
2. import java.util.List;
3. public class ForEachExample {
4. public static void main(String[] args) {
5. List<String> gamesList = new ArrayList<String>();
6. gamesList.add("Football");
7. gamesList.add("Cricket");
8. gamesList.add("Chess");
9. gamesList.add("Hocky");
10. System.out.println("------------Iterating by passing method refere
nce---------------");
11. gamesList.forEach(System.out::println);
12. }
13. }
Java Date and Time
The java.time, java.util, java.sql and java.text packages contains classes
for representing date and time. Following classes are important for
dealing with date in Java.
Java 8 Date/Time API
Java has introduced a new Date and Time API since Java 8. The
java.time package contains Java 8 Date and Time classes.
1. import java.time.LocalDate;
2. public class LocalDateExample1 {
3. public static void main(String[] args) {
4. LocalDate date = LocalDate.now();
5. LocalDate yesterday = date.minusDays(1);
6. LocalDate tomorrow = yesterday.plusDays(2);
7. System.out.println("Today date: "+date);
8. System.out.println("Yesterday date: "+yesterday);
9. System.out.println("Tomorrow date: "+tomorrow);
10. }
11. }
O/P
Today date: 2017-01-13
Yesterday date: 2017-01-12
Tomorrow date: 2017-01-14
Java StringJoiner
Java added a new final class StringJoiner in java.util package. It is used
to construct a sequence of characters separated by a delimiter. Now, you
can create string by passing delimiters like comma(,), hyphen(-) etc. You
can also pass prefix and suffix to the char sequence.
1. // importing StringJoiner class
2. import java.util.StringJoiner;
3. public class StringJoinerExample {
4. public static void main(String[] args) {
5. StringJoiner joinNames = new StringJoiner(","); // passing comma(,
) as delimiter
6.
7. // Adding values to StringJoiner
8. joinNames.add("Rahul");
9. joinNames.add("Raju");
10. joinNames.add("Peter");
11. joinNames.add("Raheem");
12.
13. System.out.println(joinNames);
14. }
15. }
Rahul,Raju,Peter,Raheem
Java StringJoiner Example: adding prefix and suffix
Java 8 Stream
Java provides a new additional package in Java 8 called java.util.stream.
This package consists of classes, interfaces and enum to allows
functional-style operations on the elements. You can use stream by
importing java.util.stream package.
o Stream does not store elements. It simply conveys elements from a source such as
a data structure, an array, or an I/O channel, through a pipeline of computational
operations.
o Stream is functional in nature. Operations performed on a stream does not modify
it's source. For example, filtering a Stream obtained from a collection produces a
new Stream without the filtered elements, rather than removing elements from the
source collection.
o Stream is lazy and evaluates code only when required.
o The elements of a stream are only visited once during the life of a stream. Like an
Iterator, a new stream must be generated to revisit the same elements of the
source.
You can use stream to filter, collect, print, and convert from one data structure to other
etc. In the following examples, we have apply various operations with the help of stream.
Java Example: Filtering Collection without using Stream
1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11. }
12. public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. List<Float> productPriceList = new ArrayList<Float>();
22. for(Product product: productsList){
23.
24. // filtering data of list
25. if(product.price<30000){
26. productPriceList.add(product.price); // adding price to a p
roductPriceList
27. }
28. }
29. System.out.println(productPriceList); // displaying data
30. }
31. }
[25000.0, 28000.0, 28000.0]
Java Stream Example: Filtering Collection by using Stream
Here, we are filtering data by using stream. You can see that code is
optimized and maintained. Stream provides fast execution.
1. import java.util.*;
2. import java.util.stream.Collectors;
3. class Product{
4. int id;
5. String name;
6. float price;
7. public Product(int id, String name, float price) {
8. this.id = id;
9. this.name = name;
10. this.price = price;
11. }
12. }
13. public class JavaStreamExample {
14. public static void main(String[] args) {
15. List<Product> productsList = new ArrayList<Product>();
16. //Adding Products
17. productsList.add(new Product(1,"HP Laptop",25000f));
18. productsList.add(new Product(2,"Dell Laptop",30000f));
19. productsList.add(new Product(3,"Lenevo Laptop",28000f));
20. productsList.add(new Product(4,"Sony Laptop",28000f));
21. productsList.add(new Product(5,"Apple Laptop",90000f));
22. List<Float> productPriceList2 =productsList.stream()
23. .filter(p -> p.price > 30000)// filtering data
24. .map(p->p.price) // fetching price
25. .collect(Collectors.toList()); // collecting as list
26. System.out.println(productPriceList2);
27. }
28. }
Java Stream Iterating Example
You can use stream to iterate any number of times. Stream provides
predefined methods to deal with the logic you implement. In the
following example, we are iterating, filtering and passed a limit to fix
the iteration.
1. import java.util.stream.*;
2. public class JavaStreamExample {
3. public static void main(String[] args){
4. Stream.iterate(1, element->element+1)
5. .filter(element->element%5==0)
6. .limit(5)
7. .forEach(System.out::println);
8. }
9. }
5
10
15
20
25
Java Stream Example: Filtering and Iterating Collection
//Findfirst()
by using Stream API solve this:.....
reduce() Method in Collection
Find Max and Min Product Price
count() Method in Collection
Convert List into Set
Convert List into Map
Method Reference in stream
normal stream and parallel stream
Java Method References
Java provides a new feature called method reference in Java 8. Method reference is used
to refer method of functional interface. It is compact and easy form of lambda expression.
Each time when you are using lambda expression to just referring a method, you can
replace your lambda expression with method reference. In this tutorial, we are explaining
method reference concept in detail.
Types of Method References
There are following types of method references in java:
1. Reference to a static method.
2. Reference to an instance method.
3. Reference to a constructor.
interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}