任何匹配值返回匹配枚举

时间:2018-04-05 18:33:33

标签: java performance stream java-stream

使用Java Streams,我想返回匹配的枚举值或抛出异常。枚举值是具有变体长度的对象数组。 对于内部过滤,使用for循环我已经实现了所需的行为,但是我如何在那里使用流呢?

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

}

2 个答案:

答案 0 :(得分:2)

可能会更清洁一点:

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

}

答案 1 :(得分:1)

你可以这样做:

Person.stream()
      .filter(x -> Arrays.stream(x.dummy)
                         .anyMatch(s -> s.equalsIgnoreCase(val)))
      .findFirst()
      .orElseThrow(() -> new IllegalArgumentException("illegal value"));