gpt4 book ai didi

java - 根据条件(Java/Guava)从列表中提取第一个匹配项?

转载 作者:行者123 更新时间:2023-12-02 06:01:20 25 4
gpt4 key购买 nike

我有以下对象的列表:

class ResourcePermissionDTO {
PermissionType permissionType;
...
}

其中 PermissionType 是以下枚举:

public enum PermissionType {
DENY, READ_ONLY, READ_WRITE;
}

所以,列表看起来像:

List<ResourcePermissionDTO> myResourcePermissions = ...

我想要的是返回在 myResourcePermissions 中找到的第一个具有最严格权限的 ResourcePermissionDTO。目前我有以下内容,但它有点困惑,我想可能有更好的方法使用 Google Guava/function idioms 来做到这一点?

private ResourcePermissionDTO returnTheFirstMostRestrictivePermissionFoundIn(final List<ResourcePermissionDTO> resourcePermissionDTOs) {
if (resourcePermissionDTOs.isEmpty()) {
return null;
}

final List<ResourcePermissionDTO> resourcePermissionDTOsWithReadWritePermissionOfDeny = Lists.newArrayList();
final List<ResourcePermissionDTO> resourcePermissionDTOsWithReadWritePermissionOfReadOnly = Lists.newArrayList();
final List<ResourcePermissionDTO> resourcePermissionDTOsWithReadWritePermissionOfReadWrite = Lists.newArrayList();

for (final ResourcePermissionDTO resourcePermissionDTO : resourcePermissionDTOs) {
switch (resourcePermissionDTO.getPermissionType()) {
case DENY:
resourcePermissionDTOsWithReadWritePermissionOfDeny.add(resourcePermissionDTO);
break;
case READ_ONLY:
resourcePermissionDTOsWithReadWritePermissionOfReadOnly.add(resourcePermissionDTO);
break;
case READ_WRITE:
resourcePermissionDTOsWithReadWritePermissionOfReadWrite.add(resourcePermissionDTO);
break;
default:
break;
}
}

if (!resourcePermissionDTOsWithReadWritePermissionOfDeny.isEmpty()) {
return resourcePermissionDTOsWithReadWritePermissionOfDeny.get(0);
} else if (!resourcePermissionDTOsWithReadWritePermissionOfReadOnly.isEmpty()) {
return resourcePermissionDTOsWithReadWritePermissionOfReadOnly.get(0);
} else if (!resourcePermissionDTOsWithReadWritePermissionOfReadWrite.isEmpty()) {
return resourcePermissionDTOsWithReadWritePermissionOfReadWrite.get(0);
} else {
return null;
}
}

最佳答案

即使采用命令式风格,也可以简化如下:

List<ResourcePermissionDTO> permissions = ...;
ResourcePermissionDTO result = null;

for (ResourcePermissionDTO p: permissions) {
if (result == null || isStronger(p.getPermissionType(), result.getPermissionType())) {
result = p;
if (result.getPermissionType() == PermissionType.DENY) break; // (1)
}
}

return result;

如果您更喜欢函数式风格,则可以使用 reduce() 重现完全相同的结果(尽管在 (1) 处没有短路优化)。 Guava 不支持 reduce(),因此以下示例使用 Java 8:

return permissions.stream().reduce((result, p) -> {
return isStronger(p.getPermissionType(), result.getPermissionType()) ? p : result;
}).orElse(null);

关于java - 根据条件(Java/Guava)从列表中提取第一个匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22657840/

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