简体   繁体   English

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

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

I want to check if a list of String contains any value that is not there in the Enum.我想检查字符串列表是否包含枚举中不存在的任何值。

public interface MyInterface {

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

public otherMethodsBelow();

} }

Below is my API where the user will pass the list of strings下面是我的 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"
}}

My requirement is if list contain any wrong value(value which is not there in MyEnum) then it should go in the else if block and if list contains the values which are also there in the MyEnum then it should go in the if block.我的要求是如果列表包含任何错误的值(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
    }
}
    

Using streams you can map MyEnum constants to a set of String使用流,您可以将 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
}

You can use Like你可以使用喜欢

if (!contains(list))

you may do as @Andy Turner suggested or您可以按照@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