JAVA 8 STREAM :
Stream is in util package of java, introduced in Java 8. Stream on data list is kind of traversing on it, we can't store the streaming data or do modification on it.
We can only apply our customised transformation and condition check to achieve our desired data out of it.
That's the reason there is a common interview questions: What are ternary operators in java stream?.
But before coming to this question let me tell you why this question is important , Stream API works in Lazy loading style , it means when there will be a ternary operator then only it will start the stream and apply intermediate logics like map(), filter etc and will return you a List , Set or any primitives value.
Lets consider below example to prove lazy loading:
List<String> list=new ArrayList<>();
list.add("Neeraj");
list.add("Chopra");
list.add("Champion");
list.stream().filter(e -> { System.out.println(e);return e.length()>0; } )
.filter(n-> n.contains("C")).findFirst();
Output :
Neeraj
Chopra
Now if i will remove the last method i.e findFirst() , output will be blank
list.stream().filter(e -> { System.out.println(e);return e.length()>0; } )
.filter(n-> n.contains("C"));
Because it didn't get any ternary operator so stream is relaxing as before, consider ternary methods as start() method of Thread, Thread will be in runnable state but it won't run until we called start() method. In case of stream same case until it is not finding any ternary operator till then it won't start the streaming.
Now coming to the previous question , all the methods returning primitive type can be consider as ternary operator along with two most important method reduce() and collect() along with other methods like findFirst, findAny(), distinct() , allMatch(), anyMatch() , noneMatch(), sorted()
There are multiple ternary operator in case of primitive return type and also specific stream type for primitive like IntStream,LongStream and DoubleStream and primitive ternary methods are like sum(), min(), max(), average() , count() etc.
List<Employee> empList=new ArrayList<>();
empList.add(new Employee(1,"Neeraj",10000));
empList.add(new Employee(2,"Chopra",20000));
empList.add(new Employee(3,"Champion",30000));
empList.add(new Employee(3,"Champion",40000));
System.out.println(empList.stream().mapToDouble(e-> e.getSalary()).max().getAsDouble());
System.out.println(empList.stream().mapToDouble(e-> e.getSalary()).min().getAsDouble());
System.out.println(empList.stream().mapToDouble(e-> e.getSalary()).average().getAsDouble());
System.out.println(empList.stream().mapToDouble(e-> e.getSalary()).sum());
System.out.println(empList.stream().mapToDouble(e-> e.getSalary()).count());
Output :
40000.0
10000.0
25000.0
100000.0
4
Now here mapToDouble is doing the conversion of employee Object stream to Double stream , same way we have mapToInt , mapToLong, flatMapToInt, flatMapToLong and flatMapToDouble.
And we have also intermediate map() method as well which can be used to convert any kind of other type to our type along with flatMap() method.
If you noticed for each map() method we have flatMap() method , so our next question is : What the difference between map() and flatMap()?
map() is used to convert list of stream to our desired data , and flatMap is used to do the same but only difference is that map() can transform only one list while flatMap() is capable of transforming multiple list.
So till now we understand map() is an intermediate method in java stream. next important intermediate method in stream is filter() which take the the input as Predicate and return either true or false which we have used in earlier example.
Lets focus on our ternary operator i.e collect() and reduce().
As we already discussed collect() is ternary operator , it helps us to convert the final desired data into our desired type it can be either List,Set or Map and it is also capable of doing sum, average, grouping and summarising(it will display min, max, avg, sum) , below are some example of collect method in which we are collecting as List, Set , Map and using grouping by method also.
List<Employee> empList = new ArrayList<>();
empList.add(new Employee(1, "Neeraj", 10000));
empList.add(new Employee(2, "Chopra", 20000));
empList.add(new Employee(6, "Chopra", 40000));
empList.add(new Employee(3, "Champion", 30000));
empList.add(new Employee(4, "Champion", 40000));
empList.add(new Employee(5, "Gold medalist Champion", 40000));
List<Employee> empp1 = empList.stream().filter(n -> n.getName().startsWith("C")).
collect(Collectors.toList());
Set<Employee> empp2 = empList.stream().filter(n -> n.getName().startsWith("C")).
collect(Collectors.toSet());
Map<Integer, Double> empp3 = empList.stream().filter(n -> n.getName().startsWith("C")).
collect(Collectors.toMap(k -> k.getEmpId(), v -> v.getSalary()));
Map<Double, List<Employee>> empp4 = empList.stream().
collect(Collectors.groupingBy(a -> a.getSalary(), Collectors.toList()));
for (Employee e : empp1) {
System.out.println("Stream as List :" + e);
}
for (Employee e : empp2) {
System.out.println("Stream as Set :" + e);
}
for (Map.Entry e : empp3.entrySet()) {
System.out.println("Stream as Map , key : " + e.getKey() + " value : " + e.getValue());
}
for (Map.Entry a : empp4.entrySet()) {
System.out.println("Stream using grouping by , key : " + a.getKey() + " value :" + a.getValue());
}
Just like groupingBy() method we can use averagingInt(int),summingInt(),summarizingInt() and same case for long and double just change the type name in method like averaging***().
IntSummaryStatistics summary = empList.stream().
collect(Collectors.summarizingInt(p -> p.getEmpId()));
System.out.println(summary);
Output: IntSummaryStatistics{count=6, sum=21, min=1, average=3.500000, max=6}
We can also use skip() and limit() methods to skip any data and limit the output of stream to a particular number.
Lets discuss now reduce() method, it is used for reducing the output of stream to a single value, it accumulate the value based on first data then add into next data it run this process entire stream and returned the final accumulated value , if no value is present then it returned the default identity value given inside reduce method :
double reduce = empList.stream().mapToDouble(i -> i.getSalary()).reduce(0, (a, b) -> a + b);
System.out.println(reduce);
Output :
180000.0
Comments
Post a Comment