繁体   English   中英

检查 Enum 是否包含列表中存在的所有值<string></string>

[英]Check if Enum contains all the values present in a List<String>

我想检查字符串列表是否包含枚举中不存在的任何值。

public interface MyInterface {

public static enum MyEnum { 
    ONE,
    TWO,
    THREE,
    FOUR;
}

public otherMethodsBelow();

}

下面是我的 API 用户将在其中传递字符串列表

@GET
@Path("/{path}")
public Response find(@QueryParam("list") final List<String> list) {
if(list contains the values that are present in MyEnum){ //if list is "ONE","THREE" then go inside if
    // do stuff
}else if(list contains any other value that is not present in MyEnum){ //if list is "ONE","FIVE" then go inside else if
    throw "Invalid Argument in list"
}}

我的要求是如果列表包含任何错误的值(MyEnum 中不存在的值),那么它应该在 else if 块中为 go,如果列表包含 MyEnum 中也存在的值,那么它应该在 if 块中为 go。

// cache enum string values to set (constant time access time)
private static final Set<String> myEnumStringValues = Arrays.stream(MyEnum.values()).map(Enum::name).collect(Collectors.toSet());

@GET
@Path("/{path}")
public Response find(@QueryParam("list") final List<String> list) {
    // O(N), where N = at most sizeof(myEnumStringValues)
    if(myEnumStringValues.containsAll(list)){ //if list is "ONE","THREE" then go inside if
        // do stuff
    }else { //if list is "ONE","FIVE" then go inside else if
        throw "Invalid Argument in list" // you can create a copy of list and call removeAll(myEnumStringValues) -> this is not always needed, I guess usually I'll have a valid case, so it is cheaper to do that operation only if it fails
    }
}
    

使用流,您可以将 map MyEnum常量转换为一组字符串

private static final Set<String> ALL_MY_ENUMS = Arrays.stream(MyEnum.values()).map(Enum::name).collect(toSet());

@GET
@Path("/{path}")
public Response find(@QueryParam("list") final List<String> list) {
    List<String> extraValues = new ArrayList<>(list);
    extraValues.removeAll(ALL_MY_ENUMS);
    if (extraValues.isEmpty()) {
        // do stuff
    } else {
        throw "Invalid Argument in list"
    }
fun contains(list: List<String>): Boolean {
    for (e: MyEnum in MyEnum.values()) {
        return list.contains(e.name)
    }
    return false
}

你可以使用喜欢

if (!contains(list))

您可以按照@Andy Turner 的建议或

Set<String> set = new HashSet<>(list);
Set<String> enumSet = Arrays.stream(RequestType.values()).map(Enum::name).collect(Collectors.toSet()));
    if (set.equals(enumSet)) {

    } else {

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM