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

Java Program : Writing First Java Factorial Program with explanation

 NAMING CONVENTION IN JAVA : Java is an object oriented programming language , we can relate it to real life object like i mapped Java with human in my previous post JAVA OVERVIEW (SESSION 1)  and represent human properties like body parts as properties in Java and Human can dance , drive , walk , run these can be mapped as Behaviour in java.    Now To represent properties and behaviour in java , there are some standard naming conventions we should follow. Class name should always starts with Uppercase letter like class Student { //Code to be executed } Properties or any kind of variables should starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ; //Code to be executed } Methods name should also starts from lower case and afterwards every first letter of each next word should be in Upper case . like class Student { int studentId ; String studentName ;

OOPS Concept in Java : ENCAPSULATION

OOPS Concept in Java : ENCAPSULATION   This OOPS concept can be used to make things simpler in case of software development . Main purpose of this concept is to hide the properties of any class and give access to fetch and modified based on business criteria.  A simple example can be a POJO ( Plain Old Java Object) in which all the properties of a class can be private and through getter and setter method of properties we can fetch and update the properties of Object. So instead of having direct access to properties we have created 2 methods to make the CLASS things encapsulated in single unit while access to it is via 2 public methods.   Just consider we have requirement that once the object is created its value should not be changed then simplest way to achieve this  can be done by just removing setter method and we will keep only getter methods to access Object properties . In this case after Object creation whatever the value of Object properties has been initialised it will b

OOPS Concept in Java : POLYMORPHISM

 POLYMORPHISM IN JAVA :  Polymorphism means mutiple forms of Single reference. And to understand in simple way just take an example from my previous post of OOPS CONCEPT IN JAVA : INHERITANCE  , I request you guys to go through this link before proceding here. So in this post I have created a method called sum() in PARENT class which has been used by CHILD class without writing same sum() method in CHILD class. This was possible becuase of INHERITANCE concept in java.  But what if CHILD class is not satisfied with PARENT sum() and CHILD class wants to improve it like by adding some message before the calculation. To do this we have another OOPS CONCEPT IN JAVA i.e POLYMORPHISM and by applying this logic we can make same sum() method behvae differently based on Object. As I mentioned earlier POLYMORPHISM means different forms and same has been achieved here by calling same sum() method but the output is different based on Object on which it has been called. If Object is of PARENT