0

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"

Diemauerdk
  • 4,347
  • 9
  • 39
  • 54

3 Answers3

2

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.

Rahul
  • 43,125
  • 11
  • 82
  • 101
2

You should add the elements to a Set which by definition requires the elements to be unique.

Jason Braucht
  • 2,350
  • 19
  • 31
1

Set contains unique elements:

Set<String> set = new HashSet<String>(list);

Then convert it to array:

String[] array = set.toArray(new String[set.size()]);
Balázs Németh
  • 5,724
  • 7
  • 43
  • 55