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
  • 3,592
  • 7
  • 34
  • 50

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.

RainMaker
  • 41,717
  • 11
  • 78
  • 97
2

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

Jason Braucht
  • 2,340
  • 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,445
  • 7
  • 40
  • 51