java 如何检查Java中ArrayList中是否有重复元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15518107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:53:52  来源:igfitidea点击:

How to check if there are duplicate elements in an ArrayList in Java

java

提问by Prasad

I have an ArrayList actors. When I print this actors variable, I get an output of like this :

我有一个 ArrayList 演员。当我打印这个角色变量时,我得到这样的输出:

Ram, cricket, Ram, chess

公羊,板球,公羊,国际象棋

I want to take only only one "Ram" instead of duplication.

我只想拿一个“Ram”而不是重复。

回答by SudoRahul

You need to use a Setinstead of a List.

您需要使用 aSet而不是 a List

From the docs:-

从文档: -

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

不包含重复元素的集合。更正式地说,集合不包含一对元素 e1 和 e2,使得 e1.equals(e2),并且最多包含一个空元素。正如其名称所暗示的那样,该接口对数学集合抽象进行建模。

回答by Divya Motiwala

You may like to use Setinstead of ArrayListas it stores unique elements.

您可能喜欢使用Set而不是ArrayList因为它存储独特的元素。

回答by MangeshBiradar

ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
   ... //Do something
}

回答by Patricia Shanahan

You should use a Set. Specifically, I suggest HashSet if order does not matter, LinkedHashSet if you want to preserve order of arrival.

你应该使用一个集合。具体来说,如果顺序无关紧要,我建议使用 HashSet,如果您想保留到达顺序,我建议使用 LinkedHashSet。

If you really need an ArrayList for other reasons, you can remove duplicates by copying to a LinkedHashSet, and then back again. That is likely to be faster than sorting and testing.

如果由于其他原因确实需要 ArrayList,则可以通过复制到 LinkedHashSet 来删除重复项,然后再返回。这可能比排序和测试更快。

回答by sagar

contains

包含

this is method available in array list go for java docs.

这是数组列表中可用的方法,可用于 Java 文档。

回答by Abhijit Mazumder

Why would you use arraylist?. Use Set.

为什么要使用arraylist?使用集。

Or if you want to know that if there are any duplicates use java.util.Collections.sort() to sort and then compare previous element to current element to find duplicates

或者,如果您想知道是否有任何重复项,请使用 java.util.Collections.sort() 进行排序,然后将前一个元素与当前元素进行比较以查找重复项

or

或者

public int getNumOfDuplicates(List<Integer> dupAraay)
{ 
  Set<Integer> yourSet = new HashSet();
  int dupFound = 0;

  for (Integer yourInt : dupAraay)
  {
   if (!set1.add(yourInt))
   {
    dupFound++;
   }
  }
  return dupFound;
}