gpt4 book ai didi

java - 当任何匹配值时返回匹配枚举

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:08 24 4
gpt4 key购买 nike

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

最佳答案

可能更简洁一些:

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

}

关于java - 当任何匹配值时返回匹配枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49679195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com