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.
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.
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.
You may like to use Set
instead of ArrayList
as it stores unique elements.
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;
}
ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
... //Do something
}
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.