If i have an ArrayList that contains "Cat" "Cat" "Dog" "Bee" "Dog" "Cat".
How can i then produce an array that contains each element exactly once in java?
I want to end up having the following array:
"Cat" "Dog" "Bee"
If i have an ArrayList that contains "Cat" "Cat" "Dog" "Bee" "Dog" "Cat".
How can i then produce an array that contains each element exactly once in java?
I want to end up having the following array:
"Cat" "Dog" "Bee"
You can use a Set
for this:-
Set<String> uniqueElements = new HashSet<String>(myList);
This Set
will now have all the Elements of your ArrayList
but without duplicates.
You should add the elements to a Set
which by definition requires the elements to be unique.
Set
contains unique elements:
Set<String> set = new HashSet<String>(list);
Then convert it to array
:
String[] array = set.toArray(new String[set.size()]);