JavaTreeSet:我想按数字进行重复检查,并按字符串排序

svgewumm  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(365)
import java.util.Comparator;
    public class Member implements Comparable<Member>{
    private int id;
    private String name;

    public Member() {}

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

    public int getID() {
        return this.id;
    }
    public String getName() {
        return this.name;
    }

    @Override
    public String toString() {
        return this.id + " : " + this.name;
    }

    @Override
    public int hashCode() {
        return this.id;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof Member) {
            Member m = (Member)obj;

            if(this.getID() == m.getID()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int compareTo(Member m) {
        return this.name.compareTo(m.getName());
    }
}

================================================

import java.util.TreeSet;
    public class TreeSetTest {
    public static void main(String[] args) {
        TreeSet<Member> ts = new TreeSet<Member>();

        ts.add(new Member(1007, "LimEunHa"));
        ts.add(new Member(1012, "JangBoYoung"));
        ts.add(new Member(1002, "AhnJinWoo"));
        ts.add(new Member(1001, "KimSiYeon"));
        ts.add(new Member(1007, "EunHa"));
        ts.add(new Member(1002, "JinWoo"));

        for(Member m : ts) {
            System.out.println(m);
        }
    }
}

=============================================

Result<br/>
1002:AhgnJinWoo<br/>
1007:EunHa<br/>
1012:JangBoYoung<br/>
1002:JinWoo<br/>
1001:KimSiYeoun<br/>
1007:LimEunHa<br/>

此代码执行排序,但允许复制。我不允许重复。我要按字符串(名称)排序,按int(id)检查重复。

jmo0nnb3

jmo0nnb31#

你可以用 ArrayList 存储成员对象的步骤

List<Member> ls = new ArrayList<Member>();

        ls.add(new Member(1007, "LimEunHa"));
        ls.add(new Member(1012, "JangBoYoung"));
        ls.add(new Member(1002, "AhnJinWoo"));
        ls.add(new Member(1001, "KimSiYeon"));
        ls.add(new Member(1007, "EunHa"));
        ls.add(new Member(1002, "JinWoo"));

从成员列表流中获取不同的成员并进行排序

ls = ls.stream().distinct().sorted().collect(Collectors.toList());

        ls.forEach(System.out::println);

输出:

1002 : AhnJinWoo
1012 : JangBoYoung
1001 : KimSiYeon
1007 : LimEunHa

相关问题