Introduction
In this post, we will explore different ways to sort Java collections in a certain order. Java platform provides a Collections framework that represents a group of objects. All the Java classes those implement the Collection interface have by default implemented the sort method i.e.Collections.sort(list/set/Array)
Java classes like String, Date, Integer, Double, Float, Long, Integer etc implements the Comparable interface by default. Java provides us with the following two interfaces to compare and sort the custom objects
Comparable Interface
public interface Comparable<T> { public int compareTo(T o); }
Java 8 also provides the built in Comparator.comparing method that returns an instance of Comparable.
Comparator Interface
Java 8 Example of Comparable Interface using lambda expressionspublic interface Comparator<T> { int compare(T o1, T o2); }In this post we will use the following student class for practice.public class Student{ public String name; public Integer age; public Student() { } public Student(String name,Integer age) { this(); this.name = name; this.age = age; } public String getName() { return name; } public Integer getAge() { return age; } @Override public String toString() { // TODO Auto-generated method stub return "Name: " + name + " ,Age: " + age; } }
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparableExample{
public static void main(String[] args) {
List students = new ArrayList();
students.add(new Student("One",4));
students.add(new Student("Two",12));
students.add(new Student("Three",9));
students.sort( (s1,s2) -> s1.age.compareTo(s2.age));
//OR Java 8 Comparator.comparing method
Collections.sort(students, Comparator.comparing(Student::getAge));
students.forEach(System.out::println);
}
}
Java 8 Example of Comparator Interface using lambda expressions
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample{
public static void main(String[] args) {
List students = new ArrayList();
students.add(new Student("One",4));
students.add(new Student("Two",12));
students.add(new Student("Three",9));
Comparator ageComparator = (s1,s2) -> s1.age - s2.age;
students.sort(ageComparator);
students.forEach(System.out::println);
//Reverse Order Sorting
students.sort(ageComparator.reversed());
System.out.println("Reverse Order Sorted List");
students.forEach(System.out::println);
}
}
Note that we have reverse sorted the collection using .reversed() method.
Comments
Post a Comment