Using Java Streams, I want to return the matching enum value or throw exception. The enum values is array of objects having variant length.
For the inner filtering, using for loop i've achieved the desired behavior, but how can I use stream there too?
public enum Person {
cat1("abc"),
cat2("def", "gh1"),
private String[] dummy;
Person(String... dummy) {
this.dummy = dummy;
}
public static Person byVal(String val) {
return Person.stream()
.filter(x -> {
here----- for(String s1 : x.dummy) {
if(s1.equalsIgnoreCase(val)) {
return true;
}
}
return false;
})
.findFirst().
orElseThrow(() -> new IllegalArgumentException("illegal value"));
}
public static Stream<Person> stream() {
return Stream.of(values());
}
}
May be a bit cleaner:
enum Person{
cat1("abc"),
cat2("def", "gh1");
private static final Set<Person> ALL = EnumSet.allOf(Person.class);
private String[] dummy;
Person(String... dummy) {
this.dummy = dummy;
}
public static Person byVal(String val) {
return ALL
.stream()
.filter(x -> Arrays.stream(x.dummy).anyMatch(y -> y.equalsIgnoreCase(val)))
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Not found : " + val));
}
}
You can do so with:
Person.stream()
.filter(x -> Arrays.stream(x.dummy)
.anyMatch(s -> s.equalsIgnoreCase(val)))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("illegal value"));
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