pablo
pablo

Reputation: 747

Convert a List<String> to a Set with Java 8

Is there a one-liner to convert a list of String to a set of enum? For instance, having:

public enum MyVal {
    ONE, TWO, THREE
}

and

List<String> myValues = Arrays.asList("ONE", "TWO", "TWO");

I'd like to convert myValues to a Set<MyVal> containing the same items as:

EnumSet.of(MyVal.ONE, MyVal.TWO)

Upvotes: 7

Views: 6830

Answers (2)

fps
fps

Reputation: 34460

Here's a two-liner (but shorter):

EnumSet<MyVal> myVals = EnumSet.allOf(MyVal.class);
myVals.removeIf(myVal -> !myValues.contains(myVal.name()));

Instead of adding elements present on the list, you could create an EnumSet with all possible values and remove the ones that are not present on the list.

Upvotes: 3

Tunaki
Tunaki

Reputation: 137084

Yes, you can make a Stream<String> of your elements, map each of them to the respective enum value with the mapper MyVal::valueOf and collect that into a new EnumSet with toCollection initialized by noneOf:

public static void main(String[] args) {
    List<String> myValues = Arrays.asList("ONE", "TWO", "TWO");
    EnumSet<MyVal> set =
        myValues.stream()
                .map(MyVal::valueOf)
                .collect(Collectors.toCollection(() -> EnumSet.noneOf(MyVal.class)));
    System.out.println(set); // prints "[ONE, TWO]"
}

If you are simply interested in having a Set as result, not an EnumSet, you can simply use the built-in collector Collectors.toSet().

Upvotes: 21

Related Questions