Features of Java 1.8
Features of Java 1.8
8 as
Functional Interface
It can have any number of default, static methods but can contain only one
abstract method.
Example-
package com.test;
@FunctionalInterface
public interface Test {
package com.test;
@Override
public void getStudentName(String name) {
System.out.println(name);
}
Lambda Expression-
Why?
Less coding
() -> {
//Body of no parameter lambda
}
(p1) -> {
//Body of single parameter lambda
}
(p1,p2) -> {
//Body of multiple parameter lambda
}
Example-
package com.test;
package com.test;
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.
Example-
package com.test;
package com.test;
Output
this is default m1 method
forEach () method-
The Java forEach() method is a utility function to iterate over a collection such
as (list, set or map) and stream. It is used to perform a given action on each the
element of the collection.
package com.test;
import java.util.HashMap;
import java.util.Map;
map.put("10", "ram");
map.put("11", "shyam");
map.put("12", "ganesh");
Output
Key = 11, Value = shyam
Key = 12, Value = ganesh
Key = 10, Value = ram
Optional class-
Java introduced a new class Optional in jdk8. It is a public final class and used to
deal with NullPointerException in Java application.
You must import java.util package to use this class. It provides methods which
are used to check the presence of value for particular variable.
Why?
package com.test;
}
}
Here we are getting exception, to avoid this type of exception, we should go for
optional class
package com.test;
import java.util.Optional;
}
}
Output
string value is not present.
Example
import java.util.StringJoiner;
Output
Ram,Shyam,ashok,ajay
Stream API
The Stream API is used to process collections of objects. A stream is a
sequence of objects that supports various methods which can be pipelined to
produce the desired result.
Different Operations On Streams-
Intermediate Operations:
1. map: The map method is used to returns a stream consisting of the
results of applying the given function to the elements of this stream.
List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x-
>x*x).collect(Collectors.toList());
Terminal Operations:
1. collect: The collect method is used to return the result of the
intermediate operations performed on the stream.
List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x-
>x*x).collect(Collectors.toSet());
class Demo
{
public static void main(String args[])
{
System.out.println(even);
}}
Output