Convert <String> List to Set with Java 8

Is there one single-liner to convert a String list to an enum set? For example, having:

public enum MyVal { ONE, TWO, THREE } 

and

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

I would like to convert myValues to Set<MyVal> containing the same elements as:

 EnumSet.of(MyVal.ONE, MyVal.TWO) 
+7
java java-8
source share
2 answers

Yes, you can make a Stream<String> your elements, map each of them to the corresponding enumeration value using mapper MyVal::valueOf and assemble it into a new EnumSet with toCollection initialized to 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're just interested in having Set , not EnumSet , you can just use the built-in Collectors.toSet() collector.

+20
source share

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

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

Instead of adding items that are in the list, you can create an EnumSet with all possible values โ€‹โ€‹and remove those that are not in the list.

+2
source share

All Articles