223

Is there some one-liner bridge method to dump a given Enumeration to java.util.List or java.util.Set?

Something built-in like Arrays.asList() or Collection.toArray() should exist somewhere, but I'm unable to find that in my IntelliJ debugger's evaluator window (and Google/SO results, too).

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Anton Kraievyi
  • 4,182
  • 4
  • 26
  • 41

6 Answers6

401

You can use Collections.list() to convert an Enumeration to a List in one line:

List<T> list = Collections.list(enumeration);

There's no similar method to get a Set, however you can still do it one line:

Set<T> set = new HashSet<T>(Collections.list(enumeration));
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
30

How about this: Collections.list(Enumeration e) returns an ArrayList<T>

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Nate W.
  • 9,141
  • 6
  • 43
  • 65
10

If you need Set rather than List, you can use EnumSet.allOf().

Set<EnumerationClass> set = EnumSet.allOf(EnumerationClass.class);

Update: JakeRobb is right. My answer is about java.lang.Enum instead of java.util.Enumeration. Sorry for unrelated answer.

Timur Levadny
  • 510
  • 4
  • 13
  • 3
    I'm pretty sure the asker was asking about java.util.Enumeration, the legacy cousin of Iterator, not java.lang.Enum, the thing you get when you use the 'enum' keyword. – JakeRobb Feb 23 '17 at 14:30
  • I did a google search for "java convert enum into a set" and this thread came back as the first response. @Timur gets my upvote. – ShellDude Dec 29 '19 at 06:35
5

When using guava (See doc) there is Iterators.forEnumeration. Given an Enumeration x you can do the following:

to get a immutable Set:

ImmutableSet.copyOf(Iterators.forEnumeration(x));

to get a immutable List:

ImmutableList.copyOf(Iterators.forEnumeration(x));

to get a hashSet:

Sets.newHashSet(Iterators.forEnumeration(x));
Alexander Oh
  • 24,223
  • 14
  • 73
  • 76
1

There's also in Apache commons-collections EnumerationUtils.toList(enumeration)

wi2ard
  • 1,471
  • 13
  • 24
-2

I needed same thing and this solution work fine, hope it can help someone also

Enumeration[] array = Enumeration.values();
List<Enumeration> list = Arrays.asList(array);

then you can get the .name() of your enumeration.

S_intg
  • 182
  • 1
  • 10
  • 5
    Your answer shows how to convert an array into a list and it only happens that you have an array of Enumerations. The question was about Enumeration->List conversion. – kryger Sep 08 '16 at 07:56