Sorting using java 8 streams

Tue, Nov 19, 2019

Read in 2 minutes

Lets see about What is the stream? and Difference between java 8 sorting and lower version (java 7 ) sorting

In my previous blog, you have seen how to sort the objects.

In this blog, we will see how to sorting with streams.

What is the stream?

Streams are like a wrapper around the data source .with its help, bulk processing on the data source can be fast.

Generally, when you want to perform operations on the collection of items, you will iterate value by value and perform the operation and print the result. To do this with effective way streams API is useful. Streams form a wrapper between the data source and data. This stream has operation methods like forEach, filter, map, peek, etc.

Difference between java 8 sorting and lower version (java 7 ) sorting:

In the lower version of java, you have to implement the comparator or comparable interfaces. But with Java 8 streams, you don’t need to implement any interfaces.

java 8 stream sorting :

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class StreamsDemo {
static List<Student> createStream(){
Student arr[]= {new Student(10,"ra","ECE"),
		new Student(20,"yy","jg"),
		new Student(30,"ra","ECE"),
		new Student(12,"yyd","jg"),
		new Student(2,"yy","jg"),
		new Student(3,"ra","ECE"),
		new Student(4,"yyd","jg")};
	List<Student> studentList = Arrays.asList(arr);
	List<Student> sortedList = studentList.stream()
		.sorted(Comparator.comparingInt((Student::getId)))
			.collect(Collectors.toList());
	return sortedList;
	}
public static void main(String args[]) {
	List<Student> l=createStream();
	for(int i = 0;i<l.size();i++) {
	System.out.println(l.get(i).getId()+","+l.get(i).getName());
	}
}
}