识别列表中的重复项 [英] Identify duplicates in a List

查看:27
本文介绍了识别列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数类型的列表,例如:

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).

所以只需遍历所有值:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆