集合list和set排序的实现

List、Set的相同点和区别

List和Set继承了Collection接口。
List以特定索引来存取元素,可以有重复元素。Set不能存放重复元素(用对象的equals()方法来区分元素是否重复)。

TreeSet的排序实现:

package com.example.demo.model;

/**
 * @author AxeLai
 * @date 2019-04-22 18:47
 */

public class User implements Comparable {
    /**
     * 编号
     */
    private int id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private String sex;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

    @Override
    public int compareTo(User user) {
        //升序排序
        return this.id - user.id;
        //降序排序
        //return this.age - o.age;
    }
}

        Set userList = new TreeSet<>();
        userList.add(new User(1,"小李","男"));
        userList.add(new User(5,"小李","男"));
        userList.add(new User(7,"小李","男"));
        userList.add(new User(3,"小李","男"));
        for (User user:userList) {
            System.out.println(user.getId());
        }

ArraList的排序:

比较的对象类

package com.example.demo.model;

/**
 * @author AxeLai
 * @date 2019-04-22 18:47
 */

public class User {
    /** 编号 */
    private int id;
    /** 姓名 */
    private String name;
    /** 年龄 */
    private String sex;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

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

比较的实现方法

    private static void sortList() {
        ListuserList = new ArrayList<>();
        userList.add(new User(1,"小李1","男"));
        userList.add(new User(5,"小李2","男"));
        userList.add(new User(7,"小李3","女"));
        userList.add(new User(3,"小李4","男"));
        //通过sort方法的第二个参数传入一个Comparator接口对象 相当于是传入一个比较对象大小的算法到sort方法中
        Collections.sort(userList,new Comparator() {
            @Override
            public int compare(User user0, User user1) {
                //降序排序
                return user1.getId()-user0.getId();
            }
        });
        for (User user:userList) {
            System.out.println(user.getId());
        }
    }

你可能感兴趣的:(集合list和set排序的实现)