2Big2BeSmall
2Big2BeSmall

Reputation: 1378

Collections.sort on list of object java

I'm need to make sure i understand correctly someone else code at work this block sort this object: theObjectList by the variable getId() what do i need to do in order to add another variable to the sorting ? for example getName()

    protected void fillData(List<AnyObject> theObjectList) {
        Collections.sort(theObjectList, (A, B) -> A.getId() - B.getId());
/*  more code */
}

Upvotes: 0

Views: 55

Answers (2)

Ravindra HV
Ravindra HV

Reputation: 2608

Believe you'd need to understand and pickup lambda expressions. They have been introduced since jdk8.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

You can use Comparators.comparing

Collections.sort(theObjectList, 
                 Comparator.comparing(x -> x.getId()).andThen(x -> x.getName()));

Upvotes: 3

Related Questions