Sometimes I have to compare a list of my POJOs using more than a single field, for example, first by a boolean isExternal()
field and then by a String getName()
field.
I wonder if there are known compare utility for doing that?
Code Snippet:
@Override
public int compare( CompanyProject o1, CompanyProject o2 ) {
return CompareBuilder.compareBoolean(o1.isExternal(), o2.isExternal()).compareString(o1.getName(), o2.getName()).getResult();
}
Don't want to write a bicycle :)
You probably want Apache Commons Lang CompareToBuilder
.
Java 8 has some functions that allow construction and chaining of Comparators:
Comparator.comparing(Pojo::isExternal)
.thenComparing(Pojo::getName);
http://download.java.net/jdk8/docs/api/java/util/Comparator.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With