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
  • 5,238
  • 9
  • 40
  • 56

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
  • 44,383
  • 11
  • 84
  • 103
2

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

Jason Braucht
  • 2,358
  • 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
  • 6,222
  • 9
  • 45
  • 60