If I have the following class:
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
How can I use comparator that compares by name, then age, then id?
You can also implement the Comparable Interface in your class.
for example, something like this:
so you don't have to implement a extra class to compare your Employees.
guava ComparisonChain:
Implement it
Use :
Read Sorting an ArrayList of Contacts , this must help you and you will get more ideas and different different types of use of Comparator.
Update
Came across this a moment ago: How to compare objects by multiple fields One of the answers linked to ComparatorChain which will invoke multiple comparators in sequence until a non-zero result is received from a comparator or all comparators are invoked. This should probably be your preferred solution.
Perhaps this (untested) implementation of
Comparator#compare()
will do the trick.You need to implement it so that it orders by preferred elements. That is, you need to compare by name, then if that comparison is equal, compare by age, etc. An example is listed below:
The Comparator interface defines two methods:
compare()
andequals()
.The
compare()
method, compares two elements for order:int compare(Object obj1, Object obj2)
obj1
andobj2
are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.By overriding
compare()
, you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.The
equals()
method, tests whether an object equals the invoking comparator:boolean equals(Object obj)
obj
is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.Example:
Check it out for more Java Comparator examples.