Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare utils for Comparators

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 :)

like image 584
Mikhail Kopylov Avatar asked Nov 30 '22 02:11

Mikhail Kopylov


2 Answers

You probably want Apache Commons Lang CompareToBuilder.

like image 89
chrylis -cautiouslyoptimistic- Avatar answered Dec 05 '22 11:12

chrylis -cautiouslyoptimistic-


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

like image 23
Stuart Marks Avatar answered Dec 05 '22 11:12

Stuart Marks