gpt4 book ai didi

java - Java中仅提取列表中重复的元素

转载 作者:行者123 更新时间:2023-12-01 18:36:06 24 4
gpt4 key购买 nike

Java 列表具有重复的元素,例如

[cat, apple, iphone, football, apple, adam, apple, football, cat, people, cat]
  • cat重复3次
  • football重复2次
  • apple重复3次

如何从列表中仅提取重复元素,以便最终列表具有 [cat, apple, football]

最佳答案

使用设置:

List<String> findDuplicates(List<String> original) {
Set<String> seen = new HashSet<String>();
Set<String> seenTwice = new HashSet<String>();

for (String s: original) {
if (!seen.add(s)) {
seenTwice.add(s);
}
}
return new ArrayList<String>(seenTwice);
}

关于java - Java中仅提取列表中重复的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950349/

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