HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Using Comparator with 3 conditions at the same time

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
samethewithtimeusingconditionscomparator

Problem

I am trying to create a class which implements the Comparator class.

The thing is that I have a list with some objects. This object is composed of 3 fields (Strings). My purpose is to sort the list based first on the first field: if the first field is the same on the two objects that I am comparing at the moment, then compare the second item of the 2 objects and finally if both fields are the same, compare the third field of the objects.

This is what I have done but I do not know if this is the correct answer:

public class MyComparator implements Comparator{

    @Override
    public int compare(final Dto address1, final Dto address2) {
        int result = 0;

        if (dto instanceof Dto) {
            final Dto dto = (Dto) address;
            final Dto dto2 = (Dto) address2;
            if(dto.getName()  dto2.getName()) {
                result = 1;
            } else {
                result = 0;
            }
        } 
//if the Names are the same then compare the Number
            if (result == 0) {
                if(dto.Number()  dto2.Number()) {
                    result = 1;
                } else {
                    result = 0;
                }
            } 
        //if the Numbers are the same then compare the Other Field

        if (result == 0) {
            if(dto.Other()  dto2.Other()) {
                result = 1;
            } else {
                result = 0;
            }
        } 

return result

}


Then I will use the following way in my service:

Collections.sort(out,new MyComparator());

Solution

The shortest way to do this is using the Java 8 Comparator building api :

Comparator myComparator = Comparator.comparing(Dto::getName)
    .thenComparing(Dto::Number)
    .thenComparing(Dto::Other);


And this is even a lot more readable.

Btw : your method names do not follow Java coding conventions, and the posted code doesn't actually compile.

Code Snippets

Comparator<Dto> myComparator = Comparator.comparing(Dto::getName)
    .thenComparing(Dto::Number)
    .thenComparing(Dto::Other);

Context

StackExchange Code Review Q#72273, answer score: 5

Revisions (0)

No revisions yet.