【问题标题】:Combining duplicate objects(POJO) within an ArrayList and generating a third and new Object Java在 ArrayList 中组合重复对象 (POJO) 并生成第三个新对象 Java
【发布时间】:2012-03-12 21:27:45
【问题描述】:

我有一个 ArrayList。它将在该数组列表中有重复的对象。副本位于“firstId”字段中。会有另一个领域, 但这不会用于比较对象相等性。找到重复项后,我需要将两者的信息结合起来,并用 3 个字段填充不同的对象。

这就是我想做的事

ClassA
{
private string firstId;
private String secondId;

//equals() and hashcode() override code for firstId;
}

ClassB
{
private string firstId;
private String secondId;
private string thirdID;
}


Class A cls1A = new ClassA();
Class A cls2A = new ClassA();

ClassB clsB = new ClassB();


if(cls1A.equals(cls2A))
{
clsB.setFirstId(cls1A.getFirstId());
clsB.setSecondId(cls1A.getSecondId());
clsB.setThirdId(cls2A.getSecondID());
}

我已经编写了很多代码来识别重复项(基本上是尝试将其添加到哈希集中,然后再次从 arraylist 和哈希集对象中获取它,匹配每个对象并尝试创建第三个对象。但是有很少有错误,这也让我的程序很慢。有没有更好的解决方案?

【问题讨论】:

    标签: arraylist duplicates pojo


    【解决方案1】:

    您确实需要一种简单的方法来将具有相同 firstId 值的对象组合在一起。两种可能的方法:

    1. 对您的 ArrayList 进行排序(使用仅查看 firstId 的 Comparator),然后遍历排序列表,保留对您找到的最后一项的引用。如果 firstId 上的最后一项和当前项匹配,则创建一个新的 ClassB。

    2. 使用带有 String 键和 Set 值的 HashMap 代替 HashSet。遍历 ArrayList,在其中存储从 firstId 值到使用该 firstId 找到的所有 secondId 值的映射。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多