[英]Java 8: Stream a list and map to another list based on different filters
我有以下代碼:
public boolean foo(List<JSONObject> source, String bar, String baz) {
List<String> myList = newArrayList();
source.forEach(json -> {
if (!(json.get(bar) instanceof JSONObject)) {
myList.add(json.get(bar).toString());
} else {
myList.add(json.getJSONObject(attribute).get("key").toString());
}
});
/**
* do something with myList and baz
*/
}
我只是想知道是否有辦法使用過濾器來內聯if-else
條件。
有點像:
List<String> myList = source.stream()
.filter(json -> !(json.get(bar) instanceof JSONObject))
.map(item -> item.get(attribute).toString())
.collect(Collectors.toList());
如果我按照上面的方法進行,我將錯過應該是“其他”的條件。 如何使用更多java-8
方式實現我想要的功能?
提前致謝!
我看到的唯一方法是將條件置於map
調用中。 如果使用filter
則會丟失“其他”部分。
List<String> myList = source.stream()
.map(item -> {
if (!(item.get(bar) instanceof JSONObject)) {
return item.get(bar).toString();
} else {
return item.getJSONObject(attribute).get("key").toString();
}
})
.collect(Collectors.toList());
或者,正如Holger在評論中建議的那樣,使用三元條件運算符:
List<String> myList = source.stream()
.map(i -> (i.get(bar) instanceof JSONObject ? i.getJSONObject(attribute).get("key") : i.get(bar)).toString())
.collect(Collectors.toList());
這樣的事情怎么樣?
List<String> myList = source.stream()
.map(json -> !(json.get(bar) instanceof JSONObject) ?
json.get(bar).toString() :
json.getJSONObject(attribute).get("key").toString())
.collect(Collectors.toList());
沒有經過測試,但你明白了。
你可以使用帶有Predicate
的函數partitioningBy
並返回Map<Boolean, List<T>>
。 true
鍵包含謂詞為true的值, false
鍵包含其他值。
所以你可以像這樣重寫你的代碼:
Map<Boolean, List<String>> partition = source.stream()
.collect(Collectors.partitionBy(json -> !(json.get(bar) instanceof JSONObject));
在這種情況下,無需使用過濾功能。
List<String> valuesWhenTrue = partition.get(Boolean.TRUE).stream().map(item -> item.get(attribute).toString()).collect(Collectors.toList());
List<String> valuesWhenFalse = partition.get(Boolean.FALSE).stream().map(json.getJSONObject(attribute).get("key").toString()).collect(Collectors.toList());
如何將if-else提取到私有函數中
private String obtainAttribute(JSONObject json){
if (!(json.get(bar) instanceof JSONObject)) {
return json.get(bar).toString();
}
return json.getJSONObject(attribute).get("key").toString();
}
並在你的lambda表達式中調用它。
List<String> myList = source.stream()
.map(item -> obtainAttribute(item))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.