Sorting in Java8 using streams!
Streams is a Java8 feature which is used to process a collection of objects. It’s functional in nature, so we can perform different operations using stream without actually modifying the source object.
// create a list of integersList<Integer> number = Arrays.asList(2,3,4,5);// demonstration of map methodList<Integer> square = number.stream().map(x -> x*x).collect(Collectors.toList());System.out.println(square); // [4,9,16,25]
Lambdas is also a Java8 feature which is used to pass function as code. Lambda expressions provide the implementation of a functional interface.
interface FuncInterface {
// An abstract function
void abstractFun(int x);
}class Test{
public static void main(String args[]) {
FuncInterface fobj = (int x)-> System.out.println(3*x);
// This calls above lambda expression and prints 15.
fobj.abstractFun(5); }}
Sorting of a custom object can be done using Comparator and Comparable.
If we need to sort based on multiple variable, we use Comparator. If sorting is to be done on a single variable then we prefer Comparable as the logic for sorting is inside the user defined object itself.
Check this for more on Comparator & Comparable.
Sorting in Java 8 :
To sort in Java8 we can use an intermediate operation of Stream API : sorted()
// create a list of integers
List<Integer> number = Arrays.asList(6,1,2,4);
// demonstration of sorted method
List<Integer> square = number.stream().sorted().
collect(Collectors.toList());
System.out.println(square); // 1,2,4,6
Let’s look at the code for sorting of a User defined class. Here we are sorting based on age variable in User class :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Sorting {
public static void main(String[] args) {
List<User> userList = new ArrayList<>(Arrays.asList(
new User("Tim" , 42),
new User("Steve", 69),
new User("Ted", 42),
new User("Andrew", 57)
));
List<User> sortedList = userList.
stream(). sorted(Comparator.comparingInt(User::getAge)). collect(Collectors.toList());
for(User user : sortedList) {
System.out.println(" Age : " + user.getAge() + " Name : " + user.getName());
}
}
}
class User {
private int age;
private String name;
User(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
To sort based on multiple variables, we will pass our own instance of Comparator object to the sorted().
List<User> sortedList = userList.
stream().
sorted((u1, u2) -> {
if(u1.getAge() == u2.getAge()) {
return
u1.getName().compareTo(u2.getName());
} else if (u1.getAge() > u2.getAge()) {
return 1;
} else
return -1;
}
).collect(Collectors.toList());
In the above code, we are comparing based on age and name. So if the age of two users are similar, then we will compare it based on the name.
Complete code :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Sorting {
public static void main(String[] args) {
List<User> userList = new ArrayList<>(Arrays.asList(
new User("Tim" , 42),
new User("Steve", 69),
new User("Ted", 42),
new User("Andrew", 57)
));
List<User> sortedList = userList.
stream().
sorted((u1, u2) -> {
if(u1.getAge() == u2.getAge()) {
return u1.getName().compareTo(u2.getName());
} else if (u1.getAge() > u2.getAge()) {
return 1;
} else
return -1;
}
).collect(Collectors.toList());
for(User user : sortedList) {
System.out.println(" Age : " + user.getAge() + " Name : " + user.getName());
}
}
}
class User {
private int age;
private String name;
User(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}Output :
Age : 42 Name : Ted
Age : 42 Name : Tim
Age : 57 Name : Andrew
Age : 69 Name : Steve
As the age of Ted and Tim are similar, so sorting was done based on the name. lexicographically Ted is smaller than Tim, so Ted is before Tim in sorted list.
Conclusion
Happy Learning. Please reach out to me of any queries. All the claps and follows are highly appreciated!