Washington Reis D F
Washington Reis D F

Reputation: 79

Collections sort Java

Hi guys i have 3 Collections, the first one I want sort per name, the second for email then last one I want sort for age. My question is it work using collections?

if I do it in sql like

sort by name,email,age

I know that it work right?

Im trying do it in java like this.

Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        return o1.getName().compareTo(o2.getName());
    }
});

//then

Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        return o1.getEmail().compareTo(o2.getEmail());
    }
});

//and then 

Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        return o1.getAge().compareTo(o2.getAge());
    }
});

it work? or each collection Overwrite previous?

Upvotes: 0

Views: 191

Answers (2)

Zabuzard
Zabuzard

Reputation: 25903

If you successively sort the same collection than the operations will override the effects of the other sorting operations.


What you want can be accomplished by adjusting your custom comparator. First compare for the name, if elements are equal then compare by email, if again equal compare by age.

Take a look at this code snippet:

Collections.sort(listPeople, new Comparator<People>() {
    @Override
    public int compare(final People o1, final People o2) {
        int nameOrder = o1.getName().compareTo(o2.getName());
        if (nameOrder != 0) {
            return nameOrder;
        }

        // Elements names are equal, compare by their email
        int emailOrder = o1.getEmail().compareTo(o2.getEmail());
        if (emailOrder != 0) {
            return emailOrder ;
        }

        // Elements emails are equal, compare by their age
        int ageOrder = o1.getAge().compareTo(o2.getAge());
        // Return that in any case as we do not have another sorting criteria
        return ageOrder;
    }
});

Since Java 8 you can achieve the same with less code (see the answer of @Eugene):

Comparator.comparing(People::getName)
    .thenComparing(People::getEmail)
    .thenComparing(People::getAge));

This will create the same comparator than explained above.

Upvotes: 4

Eugene
Eugene

Reputation: 120848

If I got it correct, you should be using the java-8 features here...

Collections.sort(listPeople, Comparator.comparing(People::getName)
                     .thenComparing(People::getEmail)
                     .thenComparing(People::getAge));

Upvotes: 6

Related Questions