Convert Enumeration to a Set/List
Asked Answered
C

6

231

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).

Counterblast answered 10/4, 2011 at 9:17 Comment(0)
M
411

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));
Milwaukee answered 10/4, 2011 at 9:20 Comment(1)
Somehow I missed this method while lurking in the autocompletion dropdown. Thanks!Counterblast
G
31

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

Griseofulvin answered 10/4, 2011 at 9:20 Comment(0)
B
11

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.

Beady answered 4/1, 2017 at 20:46 Comment(2)
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.Sapiential
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.Coed
W
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));
Woodie answered 18/4, 2017 at 12:39 Comment(0)
M
1

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

Mascle answered 31/3, 2021 at 14:51 Comment(0)
M
-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.

Middlings answered 4/6, 2015 at 9:27 Comment(1)
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.Gagnon

© 2022 - 2025 — McMap. All rights reserved.