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

5
  • 3
    Use a Set instead of a List and you're done. Commented Mar 20, 2013 at 7:57
  • same with: stackoverflow.com/questions/15518107/… Commented Mar 20, 2013 at 8:01
  • @Foredoomed I don't want to remove element. I just want to know if there is a duplicate entry in an ArrayList. Commented Mar 20, 2013 at 8:05
  • Sorry for the wrong url, it should be stackoverflow.com/questions/562894/… Commented Mar 20, 2013 at 8:07
  • Prasad,Please see my answer to find if there is any duplicate Commented Mar 20, 2013 at 8:10

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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

Comments

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.

Comments

1

contains

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

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.