Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return matching enum when any matching value

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());
    }

}

like image 796
Novice User Avatar asked May 02 '26 14:05

Novice User


2 Answers

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));
    }

}
like image 115
Eugene Avatar answered May 05 '26 04:05

Eugene


You can do so with:

Person.stream()
      .filter(x -> Arrays.stream(x.dummy)
                         .anyMatch(s -> s.equalsIgnoreCase(val)))
      .findFirst()
      .orElseThrow(() -> new IllegalArgumentException("illegal value"));
like image 28
Ousmane D. Avatar answered May 05 '26 03:05

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!