gpt4 book ai didi

java - 使用条件java删除重复的列表对象

转载 作者:行者123 更新时间:2023-12-02 03:22:57 26 4
gpt4 key购买 nike

我有数组列表对象,但我想过滤删除数据(如果一天内有任何重复的 ID)。

这是我的代码

public static void main(String[] args) {

ArrayList<UniqueCompletedChat> al = new ArrayList<UniqueCompletedChat>();
al.add(new UniqueCompletedChat("2015-11-01", "D01"));
al.add(new UniqueCompletedChat("2015-11-01", "D01"));
al.add(new UniqueCompletedChat("2015-11-01", "D02"));
al.add(new UniqueCompletedChat("2015-11-01", "D01"));
al.add(new UniqueCompletedChat("2015-11-02", "D01"));
al.add(new UniqueCompletedChat("2015-11-02", "D02"));
al.add(new UniqueCompletedChat("2015-11-02", "D03"));
al.add(new UniqueCompletedChat("2015-11-02", "D02"));
al.add(new UniqueCompletedChat("2015-11-02", "D02"));
al.add(new UniqueCompletedChat("2015-11-03", "D01"));

List<UniqueCompletedChat> result = new ArrayList<UniqueCompletedChat>();
Set<String> titles = new HashSet<String>();

for (UniqueCompletedChat u : al) {
if (titles.add(u.getIdDoctor()) || titles.add(u.getDate())) {
result.add(u);
}
}

for(UniqueCompletedChat u : result){
System.out.print(u.getDate() + " || ");
System.out.print(u.getIdDoctor());
System.out.println("");
}
}

class UniqueCompletedChat {
private String date;
private String idDoctor;

public UniqueCompletedChat(String date, String idDoctor) {
this.date = date;
this.idDoctor = idDoctor;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String getIdDoctor() {
return idDoctor;
}

public void setIdDoctor(String idDoctor) {
this.idDoctor = idDoctor;
}
}

这是我的代码的输出

enter image description here

我的目标期望结果

enter image description here

如何达到我的期望?有什么方法可以优雅地解决这个问题吗?

最佳答案

我认为该错误来自此 LOC:

if (titles.add(u.getIdDoctor()) || titles.add(u.getDate())) {
result.add(u);
}

尝试像这样组合并检查它:

if (titles.add(u.getIdDoctor() + u.getDate())) {
result.add(u);
}

当然,您可以使用 StringBuilder 以获得更好的性能。

关于java - 使用条件java删除重复的列表对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39382069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com