How to sort by two fields in Java?

后端 未结 16 2315
离开以前
离开以前 2020-11-22 08:40

I have array of objects person (int age; String name;).

How can I sort this array alphabetically by name and then by age?

Which algorithm would

16条回答
  •  生来不讨喜
    2020-11-22 09:12

    Using the Java 8 Streams approach...

    //Creates and sorts a stream (does not sort the original list)       
    persons.stream().sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
    

    And the Java 8 Lambda approach...

    //Sorts the original list Lambda style
    persons.sort((p1, p2) -> {
            if (p1.getName().compareTo(p2.getName()) == 0) {
                return p1.getAge().compareTo(p2.getAge());
            } else {
                return p1.getName().compareTo(p2.getName());
            } 
        });
    

    Lastly...

    //This is similar SYNTAX to the Streams above, but it sorts the original list!!
    persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
    

提交回复
热议问题