Collections.sort () Sort Code Case

1, case:

Person object (name, id, age)

According to requirements, age, from small to large , equal age, according to de lexicographically name reverse order

2, case design:

     1) use an ArrayList to store Person objects,

      2) using the Collections.sort () to sort

      3) output

3, Code Share:

package CollectionDemo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
java.util.Comparator import;
class Person{
    private int id;
    private int age;
    private String name;

    public Person(int id, int age,String name){
        this.id=id;
        this.age=age;
        this.name=name;
    }
    public void setId(int id) {
        this.id = id;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void setName(String name){
        this.name=name;
    }

    public int getId() {
        return id;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

public class CollectionDemo2 {
    public static void main(String[] args){
        List<Person> arrayList =new ArrayList<>();
        arrayList.add(new Person(001,20,"yang"));
        arrayList.add(new Person(002,20,"zhang"));
        arrayList.add(new Person(003,30,"li"));
        arrayList.add(new Person(004,40,"Coco"));
        arrayList.add(new Person(005,40,"Marry"));
        Collections.sort(arrayList,new Comparator<Person>(){
            public int compare(Person o1,Person o2){
                if(o1.getAge()!=o2.getAge()){
                    return o1.getAge () - o2.getAge (); // ascending order according to age
                }else{
                    return o2.getName () compareToIgnoreCase (o1.getName ());. // According to the dictionary name reverse the sort order
                }
            }
        });
        // output
        for(Person p:arrayList){
            System.out.println(p);
        }






    }
}

 

Output:

Person{id=2, age=20, name='zhang'}
Person{id=1, age=20, name='yang'}
Person{id=3, age=30, name='li'}
Person{id=5, age=40, name='Marry'}
Person{id=4, age=40, name='Coco'}

 

 

Published 45 original articles · won praise 8 · views 5828

Guess you like

Origin blog.csdn.net/wenyunick/article/details/104345570