Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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)
like image 659
pablo Avatar asked Mar 07 '16 09:03

pablo


People also ask

Can we convert list String to Set?

Given a list (ArrayList or LinkedList), convert it into a set (HashSet or TreeSet) of strings in Java. We simply create an list. We traverse the given set and one by one add elements to the list. // Set to array using addAll() method.

Can we convert list to Set in Java?

In this, we can convert the list items to set by using addAll() method. For this, we have to import the package java. util.

How do you convert a list into a Set?

We can convert the list into a set using the set() command, where we have to insert the list name between the parentheses that are needed to be converted. Hence, in the above case, we have to type the set(the_names) in order to convert the names, present in the list into a set.


1 Answers

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

like image 186
Tunaki Avatar answered Sep 20 '22 04:09

Tunaki