Using Comparator with 3 conditions at the same time 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&lt;Object&gt;{

    @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() &lt; dto2.getName()) {
                 result = -1;
            } else if(dto.getName() &gt; dto2.getName()) {
                result = 1;
            } else {
                result = 0;
            }
        } 
//if the Names are the same then compare the Number
            if (result == 0) {
                if(dto.Number() &lt; dto2.Number()) {
                    result = -1;
                } else if(dto.Number() &gt; dto2.Number()) {
                    result = 1;
                } else {
                    result = 0;
                }
            } 
        //if the Numbers are the same then compare the Other Field

        if (result == 0) {
            if(dto.Other() &lt; dto2.Other()) {
                result = -1;
            } else if(dto.Other() &gt; dto2.Other()) {
                result = 1;
            } else {
                result = 0;
            }
        } 

return result

}


Then I will use the following way in my service:

Collections.sort(out,new MyComparator());
The shortest way to do this is using the Java 8 Comparator building api : 

Comparator&lt;Dto&gt; 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.