[wp_ad_camp_1]
Before Java 8, sorting objects in collections is a bit awkward and verbose in terms of the amount of codes you need to put in. With Java 8, things got easier because of Lambda expressions.
Basically, we are using the same interface java.util.Comparator
(i.e., no new interfaces provided) but modified to take advantage of the Lamba expressions introduced in Java 8.
Java 6 Comparator Interface
Check out the older version of java.util.Comparator
at http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Comparator.java
1 2 3 4 | public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); } |
As you can see, it only has those two abstract methods.
Using Comparator Interface with Collections
Here is an example that uses the java.util.Comparator
interface in an old way with java.util.Collections
class.
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | package com.turreta.collection.sort; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class PreJava8SortCollectionDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>(); list.add(new Student("1", "Marx", "Steve")); list.add(new Student("2", "Jose", "Mark")); Collections.sort(list, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getLastName().compareTo(o2.getLastName()); } }); for (Student student : list) { System.out.println(student); } } } |
Java 8 Comparator Interface
Here is an example that uses the new java.util.Comparator
interface using lambda expression.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package com.turreta.collection.sort; import java.util.ArrayList; import java.util.List; public class Java8SortCollectionDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>(); list.add(new Student("1", "Marx", "Steve")); list.add(new Student("2", "Jose", "Mark")); list.sort((Student s1, Student s2) -> s1.getLastName().compareTo(s2.getLastName())); for (Student student : list) { System.out.println(student); } } } |
Using Comparator Interface with Collections (Lambda version)
But the same old way can be modified a bit to use Lambda expression.
[wp_ad_camp_3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package com.turreta.collection.sort; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Java8CollectionsDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>(); list.add(new Student("1", "Marx", "Steve")); list.add(new Student("2", "Jose", "Mark")); Collections.sort(list, (Student s1, Student s2) -> s1.getLastName().compareTo(s2.getLastName())); for (Student student : list) { System.out.println(student); } } } |