识别列表中的重复项 [英] Identify duplicates in a List
本文介绍了识别列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类型为整数的列表,例如:
I have a List of type Integer eg:
[1, 1, 2, 3, 3, 3]
我想要一个方法来返回所有重复项,例如:
I would like a method to return all the duplicates eg:
[1, 3]
推荐答案
Set的方法add返回一个布尔值是否一个值已经存在不存在,如果已存在则为false,请参见设置文档)。
The method add of Set returns a boolean whether a value already exists (true if it does not exist, false if it already exists, see Set documentation).
因此,只需遍历所有的值:
So just iterate through all the values:
public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)
{
final Set<Integer> setToReturn = new HashSet();
final Set<Integer> set1 = new HashSet();
for (Integer yourInt : listContainingDuplicates)
{
if (!set1.add(yourInt))
{
setToReturn.add(yourInt);
}
}
return setToReturn;
}
这篇关于识别列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文