Reputation: 69
I have an Enum of Strings like this:
public enum SomeEnum {
STRING1("some value"),
STRING2("some other value");
STRING3("some third value");
...more strings...
private String name;
SomeEnum(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
And I have a List someStringList containing some Strings.
I want to iterate over someStringList and find the corresponding enums for it.
For example: The List contains the Strings "some value" and "some third value", then I would like to use the Java Stream-API to return me a List containing SomeEnum.STRING1 and SomeEnum.STRING3
Somehow I can't get this to work. I tried something like this:
List<SomeEnum> enumList = Stream.of(someStringList).forEach( s -> Stream.of(SomeEnum.values()).filter(w -> w.toString().equalsIgnoreCase(s)).collect(Collectors.toList()));
but this doesn't compile because it doesn't return anything. Any ideas?
Upvotes: 0
Views: 842
Reputation: 140309
Build a map from the string to the corresponding SomeEnum
value:
Map<String, SomeEnum> map =
Arrays.stream(SomeEnum.values()).collect(toMap(SomeEnum::toString, s -> s));
(This can be done once and stored)
Then you can look up in this:
List<SomeEnum> enumList = someStringList.stream().map(map::get).collect(toList());
(You may or may not want to handle the case where a string isn't found in the map: for example, you could throw an exception, or drop such elements).
Upvotes: 1
Reputation: 21124
In your SomeEnum
you can build a Map<String, SomeEnum>
from string name to enum and initialize it during class loading time. Then declare a public static method in your SomeEnum
named fromString
which returns an enum constant for a given string if one exists.
private static final Map<String, SomeEnum> stringToEnum = Arrays.stream(values())
.collect(Collectors.toMap(SomeEnum::toString, e -> e));
public static SomeEnum fromString(String name) {
return stringToEnum.get(name);
}
Then use it in your client code. Here's how it looks.
List<SomeEnum> enumList = someStringList.stream()
.map(SomeEnum::fromString)
.collect(Collectors.toList());
Upvotes: 1