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)
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.
In this, we can convert the list items to set by using addAll() method. For this, we have to import the package java. util.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With