猿问

从数组中删除重复项集列表 |数组列表<集<字符串>> tmp

我有一个字符串集的数组列表;ArrayList<Set<String>> tmp

由于我的要求,我需要使用这种类型的数据结构。如何从中删除重复项?

例如,如何转换;

[[A, B, C], [B, A, C], [C, D, E], [E, C, D]]

[[A, B, C], [C, D, E]]

我确实在这里浏览了其他类似的答案,但是它们将所有项目串联到一个列表中,对于上面的例子,我不想要这个[[A, B, C, D, E, F]]


德玛西亚99
浏览 108回答 3
3回答

慕容森

就像你从任何其他 ArrayList 中删除重复项一样...例如:tmp.stream().distinct().collect(Collectors.toList());注意:这假设列表项实现了合适的方法。正如他们应该的那样。equals

有只小跳蛙

一种方法:&nbsp; &nbsp; List<Set<String>> tmp = new ArrayList<>();&nbsp; &nbsp; tmp.add(new HashSet<>(List.of("A", "B", "C")));&nbsp; &nbsp; tmp.add(new HashSet<>(List.of("B", "A", "C")));&nbsp; &nbsp; tmp.add(new HashSet<>(List.of("C", "D", "E")));&nbsp; &nbsp; tmp.add(new HashSet<>(List.of("E", "C", "D")));&nbsp; &nbsp; Iterator<Set<String>> it = tmp.iterator();&nbsp; &nbsp; while (it.hasNext())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Set<String> currentSet = it.next();&nbsp; &nbsp; &nbsp; &nbsp; for (Set<String> set : tmp)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (currentSet != set&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; && currentSet.containsAll(set)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; && currentSet.size() == set.size())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; it.remove();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(set);输出:[[A, B, C], [C, D, E]]

潇湘沐

HashSet正在研究哈希算法,因此,如果您有两组包含相同值的字符串,则该集合的哈希码将始终相同(因为字符串在java中具有特殊分配)。所以你可以试试下面。&nbsp; &nbsp; List<Set<String>> tmp = new ArrayList<Set<String>>();&nbsp; &nbsp; tmp.add(new HashSet<>(Arrays.asList(new String[]{"A","B","C"})));&nbsp; &nbsp; tmp.add(new HashSet<>(Arrays.asList(new String[]{"B","A","C"})));&nbsp; &nbsp; tmp.add(new HashSet<>(Arrays.asList(new String[]{"C","D","E"})));&nbsp; &nbsp; tmp.add(new HashSet<>(Arrays.asList(new String[]{"E","C","D"})));&nbsp; &nbsp; List<Set<String>> list =new ArrayList<>();&nbsp; &nbsp; for(Set<String> s: tmp){&nbsp; &nbsp; &nbsp; &nbsp; if(!list.contains(s)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.add(s);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(list);结果会像[[A, B, C], [C, D, E]]
随时随地看视频慕课网APP

相关分类

Java
我要回答