简体   繁体   中英

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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM