How to sort by two fields in Java?

后端 未结 16 2216
离开以前
离开以前 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:04

    Create as many comparators as necessary. After, call the method "thenComparing" for each order category. It's a way of doing by Streams. See:

    //Sort by first and last name
    System.out.println("\n2.Sort list of person objects by firstName then "
                                            + "by lastName then by age");
    Comparator sortByFirstName 
                                = (p, o) -> p.firstName.compareToIgnoreCase(o.firstName);
    Comparator sortByLastName 
                                = (p, o) -> p.lastName.compareToIgnoreCase(o.lastName);
    Comparator sortByAge 
                                = (p, o) -> Integer.compare(p.age,o.age);
    
    //Sort by first Name then Sort by last name then sort by age
    personList.stream().sorted(
        sortByFirstName
            .thenComparing(sortByLastName)
            .thenComparing(sortByAge)
         ).forEach(person->
            System.out.println(person));        
    

    Look: Sort user defined object on multiple fields – Comparator (lambda stream)

提交回复
热议问题