-2

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

Ram, cricket, Ram, chess

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

Prasad
  • 1,188
  • 3
  • 11
  • 29

6 Answers6

6

You need to use a Set instead of 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.

Rahul
  • 44,383
  • 11
  • 84
  • 103
2

You may like to use Set instead of ArrayList as it stores unique elements.

Divya Motiwala
  • 1,659
  • 1
  • 16
  • 24
1

Why would you use arraylist?. Use Set.

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

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;
}
Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
Abhijit Mazumder
  • 8,641
  • 7
  • 36
  • 44
1
ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
   ... //Do something
}
MangeshBiradar
  • 3,820
  • 1
  • 23
  • 41
1

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

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.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
1

contains

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

sagar
  • 112
  • 9