How to sort the name along with age in java

后端 未结 8 1197
失恋的感觉
失恋的感觉 2021-01-17 23:34

I am new to Java 8. I just want to sort by the name. But the condition is: if there are duplicate names then it should be sorted according to age.

For example my inp

8条回答
  •  醉话见心
    2021-01-18 00:05

    You need to compare for names first. If the names are the same, then and only then the result depends on comparing the age

    public static void main(String[] args) {
        List persons = new ArrayList<>();
        persons.add(new Person("tarun", 28));
        persons.add(new Person("arun", 29));
        persons.add(new Person("varun", 12));
        persons.add(new Person("arun", 22));
    
        Collections.sort(persons, new Comparator() {
    
            public int compare(Person t, Person t1) {
                int comp = t.getFname().compareTo(t1.getFname());
                if (comp != 0) {    // names are different
                    return comp;
                }
                return t.getAge() - t1.getAge();
            }
        });
        System.out.println(persons);
    
    }}
    

    if you want to change from ascending to descending, just change the sign. e.g.

     return -comp;
    

    or swap the person

    name

     int comp = t1.getFname().compareTo(t.getFname());
    

    age

     return t1.getAge() - t.getAge();
    

提交回复
热议问题