Tutorial by Examples

Say we are working on a class representing a Person by their first and last names. We have created a basic class to do this and implemented proper equals and hashCode methods. public class Person { private final String lastName; //invariant - nonnull private final String firstName; //in...
The Comparable<T> interface requires one method: public interface Comparable<T> { public int compareTo(T other); } And the Comparator<T> interface requires one method: public interface Comparator<T> { public int compare(T t1, T t2); } These two met...
There are two Collections.sort() methods: One that takes a List<T> as a parameter where T must implement Comparable and override the compareTo() method that determines sort order. One that takes a List and a Comparator as the arguments, where the Comparator determines the sort order. ...
As of Java 8, there are default methods on the Map.Entry interface to allow sorting of map iterations. Java SE 8 Map<String, Integer> numberOfEmployees = new HashMap<>(); numberOfEmployees.put("executives", 10); numberOfEmployees.put("human ressources", 32); numb...
Comparator.comparing(Person::getName) This creates a comparator for the class Person that uses this person name as the comparison source. Also it is possible to use method version to compare long, int and double. For example: Comparator.comparingInt(Person::getAge) Reversed order To create ...

Page 1 of 1