[英]How to simplify huge if-statement in .filter body?
是否有更好的意義更可讀的表達方式?
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 cotains:
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
類中,它看起來更好:
// 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());
假設邏輯的其余部分將對每個屬性進行順序檢查以添加到過濾條件。 您可以將此類邏輯移動到對象本身內的equals
(以及hashCode
)實現,然后再使用更簡單的流管道:
List<LocationVO> filterList(List<LocationVO> input, LocationVO elem) {
return input.stream()
.filter(o -> elem.equals(o))
.collect(Collectors.toList());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.