1

我有一个arrayLists 的arrayList。每个内部数组列表都包含一些格式为 (name.version) 的对象。

{  {a.1,b.2,c.3} , {a.2,d.1,e.1} , {b.3,f.1,z.1}....} 

例如 a.1 意味着 name = a 并且版本是 1。

所以我想消除这个列表数组列表中的重复项。对我来说,两个对象同名时是重复的

所以基本上我的输出应该是

{ { a.1,b.2,c.3},{d.1,e.1} ,{f.1 ,z.1} }

请注意,我希望以完全相同的形式输出(也就是说,我不想要一个没有重复的列表)

有人可以为此提供最佳解决方案吗?

我可以遍历每个内部列表并将内容放入哈希集中。但是那里有两个问题,我无法以列表的形式得到答案。另一个问题是,当我需要覆盖该对象的 equals 时,但我不确定这是否会破坏其他代码。如果它们的名称相同,则这些对象有意义地相等(仅在这种情况下。我不确定这是否会涵盖整个频谱)

谢谢

4

3 回答 3

3

我使用 Iterator.remove() 在您移动时修改集合。

// build your example input as ArrayList<ArrayList<String>>
String[][] tmp = { { "a.1", "b.2", "c.3" }, { "a.2", "d.1", "e.1" },
        { "b.3", "f.1", "z.1" } };
List<List<String>> test = new ArrayList<List<String>>();
for (String[] array : tmp) {
    test.add(new ArrayList<String>(Arrays.asList(array)));
}

// keep track of elements we've already seen
Set<String> nameCache = new HashSet<String>();

// iterate and remove if seen before
for (List<String> list : test) {
    for (Iterator<String> it = list.iterator(); it.hasNext();) {
        String element = it.next();
        String name = element.split("\\.")[0];
        if (nameCache.contains(name)) {
            it.remove();
        } else {
            nameCache.add(name);
        }
    }
}
System.out.println(test);

输出

[[a.1, b.2, c.3], [d.1, e.1], [f.1, z.1]]
于 2012-05-05T00:08:25.903 回答
2
List<List<Pair>> inputs; // in whatever format you have them
List<List<Pair>> uniqued = new ArrayList<>(); // output to here
Set<String> seen = new HashSet<String>();
for (List<Pair> list : inputs) {
  List<Pair> output = new ArrayList<>();
  for (Pair p : list)
    if (seen.add(p.getName()))
      output.add(p);
  uniqued.add(output);
}
于 2012-05-05T00:03:03.623 回答
1

创建一个集合。遍历列表项的列表。查看该项目是否在 Set 中。如果它已经存在,请忽略它。如果不是,请将其添加到 Set 和列表列表中。

您的方法将返回一个新的列表列表,而不是修改旧列表。在迭代列表时修改列表是一种痛苦。

于 2012-05-05T00:03:36.267 回答