In Java 8 we have a new feature called “Streams”. The “Streams” are similar to collections, but there are some differences. Primarily the collections are the data structures which will hold the data. To process the data, we need to get the data from the collections and execute some logic. For example, we have a list of Students. We need to sort the students based on the marks secured, descending order. To perform the above said logic, we have to follow the below steps.
- Create a Comparator.
package org.smarttechie; import java.util.Comparator; public class MarksComparator implements Comparator<Student>{ @Override public int compare(Student student1, Student student2) { if (student1.getTotalMarks() > student2.getTotalMarks()) { return -11; } else if (student1.getTotalMarks() < student2.getTotalMarks()) { return 1; } else { return 0; } } }
- We have to call
Collections.sort(students, new MarksComparator());
With “Streams” we can do it in a simple way. The code snippet is given below.
List<String> studentRollNumbers = students.parallelStream().sorted() .map(Student::getRollNumber) .collect(Collectors.toList());
Another usecase where we want to get the student whose name is “ABC_4”. If you use collections approach, we need to iterate the list and compare each student name with “ABC_4”. With the Streams we will do it very simple way.
boolean studentFound = students.parallelStream() .anyMatch(t -> t.getStudentName() .equalsIgnoreCase("ABC_4"));
If you look at the above code, the stream is having the flow of data and process the data on the fly to generate the result. Here each method acting on a stream is a pipeline. The output of the one pipeline becomes input to the other pipeline. You can get the stream by calling stream() or parallelStream(). If you have multi core processor system and want to utilize the CPU, then you can use parallelStream() which will use multiple threads to process the data. As a developer, you no need to write multi thread programming. If you use collections, and want to use multi core processors, then developers has to write multi threaded code.
The sample code used in this article is available here.
Leave a Reply