gpt4 book ai didi

java - 如何简化 .filter 主体中的巨大 if 语句?

转载 作者:行者123 更新时间:2023-11-29 04:11:51 26 4
gpt4 key购买 nike

是否有更好的含义和可读性更好的表达方式?

    List<LocationVO> listLocation = listLocationAll.stream().filter(l -> {
boolean ok = true;
if ( filter.getClient_id() != null && filter.getClient_id().longValue() != l.getParent_client_id() ) {
ok = false;
}
if ( filter.getLocation_id() != null && filter.getLocation_id().longValue() != l.getLocation_id() ) {
ok = false;
}
if (filter.getLocation_type() != null && (filter.getLocation_type().equals(l.getLocation_type()) == false) ) {
ok = false;
}
return ok;
}).collect(Collectors.toList());

LocationVO 包含:

public class LocationVO implements Serializable {

private static final long serialVersionUID = 1L;

private long location_id;
private long parent_client_id;
private String name;
private String location_type;
...
}

filter 是 LocationFilter 类型并且包含:

public class LocationFilter implements Serializable {

private Long client_id;
private Long location_id;
private String location_type;
}

第一个 if 语句:如果为客户端 ID 设置了过滤器 -> 不包含任何其关联客户端没有此 ID 的 LocationVO

第二个 if 语句:如果为位置设置了过滤器 -> 删除/过滤所有没有此 id 的 LocationVO

第三个if语句:过滤所有不具有过滤器 location_type 的 VO。

((我认为,没有一个是过时的((如评论中所述))))

最佳答案

您可以构建 Predicate<LocationVO分阶段:

    Predicate<LocationVO> p = l -> true;
if (filter.getClient_id() != null) {
p = p.and(l -> filter.getClient_id().longValue() != l.getParent_client_id());
}
if (filter.getLocation_id() != null) {
p = p.and(l -> l.getLocation_id().longValue() == filter.getLocation_id());
}
if (filter.getLocation_type() != null) {
p = p.and(l -> filter.getLocation_type().equals(l.getLocation_type()));
}

然后使用构建的谓词来过滤流:

    List<LocationVO> listLocation = listLocationAll.stream()
.filter(p)
.collect(Collectors.toList());

现在,如果您将谓词构建移动到 filter 中s 类,它看起来更漂亮:

    // within the class of "filter"
Predicate<LocationVO> createLocationVOPredicate() {
Predicate<LocationVO> p = l -> true;
if (getClient_id() != null) {
p = p.and(l -> getClient_id().longValue() == l.getParent_client_id());
}
if (getLocation_id() != null) {
p = p.and(l -> l.getLocation_id().longValue() == getLocation_id());
}
if (getLocation_type() != null) {
p = p.and(l -> getLocation_type().equals(l.getLocation_type()));
}
return p;
}

和用法:

    listLocation = listLocationAll.stream()
.filter(filter.createLocationVOPredicate())
.collect(Collectors.toList());

关于java - 如何简化 .filter 主体中的巨大 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54635934/

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