对象集合排序,两个属性排序

实体类

package com.funtl.hello.spring.web.admin.ribbon.Test;

public class User {

    private String name;

    private int age;

    public User(String name,int age){
        this.name = name;
        this.age = age;
    };

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

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

测试类

package com.funtl.hello.spring.web.admin.ribbon.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class SortTest {

    public static void main(String[] args) {
        ArrayList users = new ArrayList<>();
        User user1 = new User("张三1",12);
        User user2 = new User("张三2",11);
        User user3 = new User("张三3",9);
        User user4 = new User("张三4",34);
        User user5 = new User("张三5",14);
        User user6 = new User("张三7",14);
        User user7 = new User("张三6",14);
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);
        users.add(user6);
        users.add(user7);
        System.out.println("排序前:");
        for (User user : users) {
            System.out.println(user);
        }
        //按照age降序
        Collections.sort(users, new Comparator() {
            @Override
            public int compare(User o1, User o2) {
//                if (o1.getAge() < o2.getAge())
//                    return 1;
//                if (o1.getAge() > o2.getAge())
//                    return -1;
                int result = o1.getAge() > o2.getAge() ? 1 : -1 ;
                return result;
            }
        });
        System.out.println("按照age降序:");
        for (User user : users) {
            System.out.println(user);
        }
        //按照name降序
        Collections.sort(users, new Comparator() {
            @Override
            public int compare(User o1, User o2) {
                return o2.getName().compareTo(o1.getName());
            }
        });
        System.out.println("按照name降序:");
        for (User user : users) {
            System.out.println(user);
        }

        //按照age降序,age相同就按name降序
        Collections.sort(users, new Comparator() {
            @Override
            public int compare(User o1, User o2) {
                int resuelt = o1.getAge()>o2.getAge()?1:(o1.getAge()==o2.getAge()?0:-1);
                if (resuelt==0)
                    return o2.getName().compareTo(o1.getName());
                return resuelt;
            }
        });
        System.out.println("按照age降序,age相同就按name降序:");
        for (User user : users) {
            System.out.println(user);
        }

    }
}

你可能感兴趣的:(工作学习)