1. 程式人生 > >Java,List雙重排序,某值放最後或最前

Java,List雙重排序,某值放最後或最前

import java.util.*;

class User {
    private Integer age;
    private String name;

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

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

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

public class Main {
    private Integer MAXAGE = 99;
    private Integer MINAGE = 1;

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Main main = new Main();
        List<User> userList = new ArrayList<>();
        userList.add(new User(3, "Tom"));
        userList.add(new User(2, "Ana"));
        userList.add(new User(99, "Bob"));
        userList.add(new User(1, "Lyly"));
        main.f1(userList);
//        main.f2(userList);
        System.out.println(userList);
    }

    /**
     * 最大年齡放最後,最小年齡放最前,
     * 然後按照name排序,升序
     * @param userList
     */
    private void f1(List<User> userList) {
        Collections.sort(userList, new Comparator<User>() {
            @Override
            public int compare(User u1, User u2) {
                if (MAXAGE.equals(u1.getAge())) {
                    return 1;
                } else if (MINAGE.equals(u1.getAge())) {
                    return -1;
                } else {
                    return u1.getName().compareTo(u2.getName());
                }
            }
        });
    }//f1
//    [User{age=1, name='Lyly'}, User{age=2, name='Ana'}, User{age=3, name='Tom'}, User{age=99, name='Bob'}]

    
    /**
     * 只按照name排序,升序
     * @param userList
     */
    private void f2(List<User> userList) {
        Collections.sort(userList, new Comparator<User>() {
            @Override
            public int compare(User u1, User u2) {
                return u1.getName().compareTo(u2.getName());
            }
        });
    }//f2
//    [User{age=2, name='Ana'}, User{age=99, name='Bob'}, User{age=1, name='Lyly'}, User{age=3, name='Tom'}]
}