Java Comparators in a More Declarative Way
How to use the Comparator interface in Java 8 with a more intuitive and functional method.
Join the DZone community and get the full member experience.
Join For FreeJava 8 has added many intuitive utility methods in the Comparator
interface, making it easier to work with comparators in a functional way.
For example, if I want to sort the list of strings in a descending manner with length and they have the same length, I will sort in reverse natural ordering, and, I would, then, do something like this in JDK 7 or prior:
public void sortOldWay(final List < String > words) {
words.sort(new Comparator < String > () {
@Override
public int compare(String s1, String s2) {
if (s2.length() == s1.length()) {
return s1.compareTo(s2);
} else {
return s2.length() - s1.length();
}
}
});
}
You can see this approach is more imperative, focusing on how to sort the list.
But, with Java 8, rather than specifying how to do that, this can be accomplished in a more declarative way with static methodscomparing(),
and thenComparing()
reverseOrder()
as:
public void sortNewWay(final List<String> words) {
words.sort(Comparator.comparing(String::length).thenComparing(Comparator.reverseOrder()).reversed());
}
Comparator.comparing()
takes a Function
argument. The type T
is the type of object being compared and type U
is the type of object that will actually be compared. Here, T
is thestring
and, since we are comparing lengths of words, the type U
is Integer
. So, it possible to write the call to sort
even more intuitively as:
public void sortNewWayIntuitive(final List<String> words) {
final Function<String, Integer> byLength = s -> s.length();
words.sort(Comparator.comparing(byLength)
.thenComparing(Comparator.reverseOrder()).reversed());
}
Let us take this to the next level where we want Comparator
to work consistently with equals
for objects.
I want to sort the list of Student, where Student
has a name
and age
, by name
, then I need to consider age
as well or vice versa, to make Comparators
consistent with equals
as below:
public enum SORT_METHOD {
BYNAME,
BYAGE
}
public void sort(final List < Student > students, final SORT_METHOD method) {
Collections.sort(students, (s1, s2) - > {
if (SORT_METHOD.BYNAME == method) {
if (s1.getName().compareTo(s2.getName()) == 0) {
if (s1.getAge() == s2.getAge()) return 0;
else if (s1.getAge() < s2.getAge()) return -1;
else return 1;
}
return s1.getName().compareTo(s2.getName());
} else {
if (s1.getAge() == s2.getAge()) return s1.getName().compareTo(s2.getName());
else if (s1.getAge() < s2.getAge()) return -1;
else return 1;
}
});
}
This can be done in a more declarative way with comparing()
and thenComparing()
as:
public enum SORT_METHOD {
BYNAME,
BYAGE
}
Function < Student, String > byName = e - > e.getName();
Function < Student, Float > byAge = e - > e.getAge();
public void sort(final List < Student > students, final SORT_METHOD method) {
if (SORT_METHOD.BYNAME == method) {
Collections.sort(students, Comparator.comparing(byName).thenComparing(byAge));
} else {
Collections.sort(students, Comparator.comparing(byAge).thenComparing(byName));
}
}
This is a more intuitive and declarative method in comparison to the old technique.
Conclusion
There are other utility methods like thenComparingDouble()
, thenComparingLong()
, reverseOrder()
, naturalOrder()
, reversed()
, nullsFirst()
, etc., making it the easiest comparison easiest. Let me know your thoughts!
For the examples I presented above, all the source code is available on GitHub.
Opinions expressed by DZone contributors are their own.
Comments