Java 8 features
==========================================================
1)Java Functional Interface
- it is an interface that contains only one abstract method
that means it have only one function to execuate
-lambda expression ( -> ) is expressed as instance of functional interface.
- functional inteface can have any number of default(non abstarct) and static
method.
-Functional Interface is also known as Single abstarct method(SAM).
-@FunctionalInterface is annotation used to define your interface as functional
interface
Functional Interface provided by java :
1)Runnable
2)Comparable
3)ActionListener
4)callable
===================================================================================
==
@FunctionalInterface
public interface ArithematicInterface {
int calculateOperation(int a, int b);
public static void sayHi() {
[Link]("Hi");
}
public static void sayHiiii() {
[Link]("Hi");
}
default void sayHello() {
}
}
=================================================================================
public class FunctionalInterfaceExample{
public static void main(String[] args) {
ArithematicInterface add = (a, b) -> {
return a + b;
};
[Link]("Addition is :"+ [Link](2, 3));
ArithematicInterface mult = (a ,b) -> a * b;
[Link]("Multiplication is :"+ [Link](2,
3));
[Link]();
[Link]();
}==================================================================================
==
-four main kinds of functional interface
1)consumer - takes only one argument and no retun value
2)predicate - takes only one argument and retuns value ->only true/false(boolean)
3)function
4)supplier
1)consumer
Functional Varients :-
1)DoubleConsumer
ex-> DoubleConsumer dc =(d) ->[Link](d+d);
[Link](4);
// creating instance of doubleConsumer
DoubleConsumer dcMul = (o)->[Link](o*o);
DoubleConsumer dcPlus =(d) ->[Link](d+d);
//uses andThen() method
DoubleConsumer combine = [Link](dcPlus);
[Link](5);
2)IntConsumer
ex -> IntConsumer ic = (x) ->[Link](x*x);
[Link](4);
3)LongConsumer
LongConsumer lc =(l) ->[Link](l+l);
[Link](9);
4)Bi-Consumer - takes two argument, no return value
BiConsumer<String, Integer> biCon = (name, sal) ->
[Link](name+" "+sal);
[Link]("Akshay", 200000);
syntax-
Consumer<Integer> consumer = (value) -> [Link](value);
-The consumer interface is mainly used to print the data,logging,modify the data o
any operation that dosent produce a
result but affect the input data.
==============================================================================
2)Predicate
- function which accepts an arguments and in return generates a boolean value as an
answer.
- takes only one argument and retuns value ->only true/false(boolean)
Functional Varients:
a)IntPredicate
ex-->
IntPredicate ip = (age) -> age >= 18;
boolean perRes =[Link](23);
[Link](perRes);
ex2 -->
IntPredicate ip1 = (age) -> {
if (age >= 18)
return true;
return false;
};
IntPredicate ip2 = (age) -> {
if (age >= 25)
return true;
return false;
};
IntPredicate ipOr = [Link](ip2);
boolean perRes = [Link](23);
[Link](perRes);
b)DoublePredicate
c)LongPredicate
d) -Bi-predicate
which accepts 2 value as an argument and returns boolean value
Syntax:
public interface Predicate<T>
{
boolean test(T t);
}
Predicate predicate =(value) -> value != null;
-Predicate are commonly used for testing conditions, data filtering from
collections and making decision based on given criteria.
===================================================================================
====
3)Function
- it receives single argument and returns a value after some processing.
Functional Varients:
1)IntFunction<Integer>
ex-->
IntFunction<Integer> ip = (u) -> u*u;
Integer resFu =[Link](4);
[Link](resFu);
2)DoubleFunction<Double>
ex-->
DoubleFunction<Double> dcFun =(pp) -> pp/2;
Double po=[Link](6);
[Link](po);
3)LongFunction<Long>
4)BiFunction<T, U, R>
it accepts two arguments and returns a value after some processing.
==============================================================================
4)Supplier
-not take any single input or arguments and not returns anything
- we used supplier when there is need of lazy genration of value.
ex->
Supplier<Double> randomValue=() -> [Link]();
[Link]([Link]());
===============================================================================
============================************************===========================
===============================================================================
2) Optional
- it is a public final class which is used to deal with null pointer exception.
-it provides methods which actually checks the presence of value for perticular
variable.
- it avoids many null checks (ex-> if(str != null).
Optional have two states
1)Present - List<Employee> emp -> [Link]();
2)Absent
String str[] = new String[10];
str[3]="abc";
Optional<String> checkNull = [Link](str[3]);
if([Link]()) {
[Link]("yes present");
}else {
[Link]("not present");
}
=============
Example 2
//*********** Throw null pointer exception*****//
// String arr[] = new String[5];
// String aa = arr[2].toUpperCase();
// [Link](aa);
//**Handled by optional***//
String arr[] = new String[5];
Optional<String> optionalCheck = [Link](arr[2]);
if([Link]()) {
String aa = arr[2].toUpperCase();
[Link](aa);
}else {
[Link]("Value not present");
}
=============================================================================
3)for each
List<String> nameList = new ArrayList<>();
[Link]("Shubham");
[Link]("Ajay");
[Link]("Vaibhav");
[Link]("Amruta");
[Link](i -> [Link](i));
[Link]([Link]::println);
===================================================================================
4)Lambda expression
syntax ->
- It is short block of code which takes in parameters and returns a value.
- it is similar to method, but they do not need a name and they can be implemented
in body of the method.
- The lambda expression is provide the implementation of interface which has
functional interface.
- It saves the code
- lambda expression is treated as function so your javac(compiler) not
create .class file
- It helps to iterate, filter and extarct data from collections.
===================================================================================
===
5)Stram API
- Stram api is newly added feature to collections api in java 8.
-Stream api is represent the sequence of elements and supports different
operations(Filter,Sort,Map, Collect)
- Stram api takes input from your collections, arrays.
-stream api dont change the original data , they only provide the result
- to reduce lines of code
two types of operation:
1)Intermediate
-filter
-map
-sorted
2)Terminal
-collect
-forEach
-reduce
===================================================================================
==
public class Java8Feaures {
public static void main(String[] args) {
//map
List<Integer> numList =[Link](2,6,8,9);
List<Integer> sqrNum = [Link]().map(x ->
x*x).collect([Link]());
[Link](sqrNum);
//filter
List<String> nameList = [Link]("Shubham","Vaibhav","Ajay","Amruta");
List<String> resList =[Link]().filter(i ->
[Link]("A")).collect([Link]());
[Link](resList);
-----------------------------------------------------------------------------------
--------------
example-->
List<String> nameList =
[Link]("Ajay","Mahesh","Ravi","Swapnesh","Sunil");
List<String> result =[Link]().filter(i ->
[Link]("S")).map(i-> [Link](" OK"))
.collect([Link]());
for(String a :result) {
[Link](a);
}
Qustion to do--
//employee - empid, name, exp,salary,age
// filter emp on exp >=30 --> increase their current salary by
10000
-----------------------------------------------------------------------------------
--------------
//sorted
List<String>sortedList
=[Link]().sorted().collect([Link]());
[Link](sortedList);
Reverse Order
List<String> nameList =
[Link]("Ajay","Mahesh","Ravi","Swapnesh","Sunil","Amit","Ishan");
List<String>sortedList
=[Link]().sorted([Link]()).collect([Link]());
for(String a :sortedList) {
[Link](a);
}
-----------------------------------------------------------------------------------
-------------
//forEach
[Link]().map(x -> x+x).forEach(y -> [Link](y));
//reduce
List<Integer> numList = [Link](2, 6, 8, 9);
int res = [Link]().filter(x -> x % 2 == 0).reduce(0, (a,b) -> a
+ b);
[Link](res);
===================================================================================
==================
-------------Example on pedicate and consumer -------------------------------
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class FunctionInterfaceTypeExamples {
public static void main(String[] args) {
//Consumer
DoubleConsumer dc = (a) -> [Link](a*5);
[Link](2);
IntConsumer ic =(b)-> [Link](b+b);
[Link](5);
BiConsumer<String, Integer> biCon = (name,salary)->
[Link](name+":"+salary);
[Link]("Manish Jha", 45000);
[Link]("===============Predicate==================");
DoublePredicate dp =(age) -> age > 18;
boolean res= [Link](12);
[Link](res);
[Link]("==================================================");
List<Integer> numbers = [Link](1,2,3,4,5,6,7,8,9,10);
//consumer
Consumer<Integer> printData = (num) -> [Link](num > 5);
[Link](printData);
//prdicate
Predicate<Integer> isEven = (number) -> number % 2 == 0;
[Link]().filter(isEven)
.forEach([Link]::println);
[Link]("========================Function======================");
IntFunction<Integer> cube = (a) -> a*a*a;
var res1 =[Link](5);
[Link]("cube is :"+res1);
BiFunction<Integer, Integer, Integer> bifunDiv = (x,y) ->x/y;
var res4 =[Link](6, 2);
[Link](res4);
GenericInterface<String, String,String> greetings =(a,b) -> b+" -->"+a;
var greet =[Link]("Good Morning", "Pranay");
[Link](greet);
[Link]("========================Supplier======================");
Supplier<Double> randomValue=() -> [Link]();
[Link]([Link]());
-------------------------------------------------------------------------------
@FunctionalInterface
public interface GenericInterface<T,U,R> {
public String sayHi(String greeting,String name);
}
==================================================
map
List<String> colorList = new ArrayList<>();
[Link]("Pink");
[Link]("Yellow");
[Link]("Red");
[Link]("Balck");
[Link]("Grey");
List res =[Link]().map(i ->
[Link]()).collect([Link]());
for(Object a : res) {
[Link](a);
}
-------------------------------------------
flat map
public static void main(String[] args) {
List<List<Integer>> number = new ArrayList<>();
List<Integer> list1 = [Link](1,2);
List<Integer> list2 = [Link](3,4);
List<Integer> list3 = [Link](5,6);
List<Integer> list4 = [Link](7,8);
[Link](list1);
[Link](list2);
[Link](list3);
[Link](list4);
[Link]("List of List ----->"+number);
List<Integer> flatMapRes =[Link]().flatMap(i ->
[Link]()).collect([Link]());
[Link]("After flat map operation-->"+flatMapRes);
//List<List<Integer>> number ==> List<Integer>
}