List去重复(多个字段)TreeSet实现

package com.company;

import java.util.TreeSet;

/**
 * @author cel
 * @describe
 * @date 2020/3/18 14:09
 */
public class User implements Comparable{
    private Integer id;
    private String name;
    private Integer age;

    @Override
    public int compareTo(Object o) {

        User u = (User)o;
        if(null != u.getAge()){
            return u.getAge().compareTo(this.getAge());
        }
        if(null != u.getName()){
            return u.getName().compareTo(this.getName());
        }
        return 0;
    }

    public User() {
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getId() {
        return id;
    }

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

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

    public static void main(String[] args) {
        TreeSet<User> ts = new TreeSet<>();

        ts.add(new User("zs",12));
        ts.add(new User("ls",13));
        ts.add(new User("zs",12));

        System.out.println(ts);
    }
}

你可能感兴趣的:(集合)