Skip to main content

JAVA 8 STREAM

 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

Popular posts from this blog

Bubble sort Implementation

Bubble sort  : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.    So time complexity for bubble sort will be O(n^2).         space complexity for bubble sort will be O(1). // Bubble Sort class BubbleSort { public static void sort ( int [] array) { int n = array. length ; while ( true ) { boolean swapped = false; for ( int i = 0 ; i < n - 1 ; i++) { if (array[i + 1 ] < array[i]) { swap (array , i , i + 1 ) ; swapped = true; } } if (!swapped) break; } } private static void swap ( int [] array , int i , int j) { int temp = array[i] ;...

Object-Oriented Programming Concept in Java

OOPS( Object-Oriented Programming ) Concept in Java :   As we all know Java is Object Oriented programming language and what exactly it means in simple words to understand can be described as whatever is going to happen by Java , it will be based on some Object.  So next question can be what is Object ? , "Object is the representation or reference of Class to access its properties and use its behaviour ", now next is What is Class in java and answer to this question is "A class in java is the blueprint of Properties and Behaviours of it's own Object" as explained in my previous post  BASIC OVERVIEW OF JAVA  (SESSION 1)   Let's understand through an example : public class FirstJavaProgram { int firstNumber=10; int secondNumber=20;      public int sum(int fNum, int sNum){         return fNum+sNum;     }     public static void main(String[] args) {     //our logics ...

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control

JAVA MEMORY LEAK, UTILISATION AND MONITORING USING JFR using Mission Control Java flight recording(JFR) help us to analyse and find the root cause of any slowness in our program along with CPU usage , hot methods and garbage collection , profiling etc. To visualise we need to feed .jfr file to JDK mission control present in JDK bin folder. After successful compilation , we should run the program with below option which will generate the .jfr and feed to mission control.   command :  j ava -XX:+UnlockCommercialFeatures -XX:+FlightRecorder  -XX:StartFlightRecording=duration=200s,filename=flight.jfr -cp ./out/ path-and-class-name Below are some example to understand how this JFR can be helpful. 1. Lets consider we have created a java program in which we have used LinkList to store the elements and in same program we are using contains method inside a for loop of 1 million , in this case each time this contains method will be called then 1 million records will be sc...