[英]Java 8 Filtering with condition and collecting custom Map
我有一些集合List<Map<String, Object>>
需要使用Java 8 lambda表達式進行過濾。 我將收到帶有標志的JSON對象,必須應用過濾條件。 如果未收到JSON對象,則不需要過濾。
protected List<Map<String, Object>> populate(List<SomeObject> someObjects, String string) {
taskList.stream()
// How to put condition here? Ho to skip filter if no filter oprions are received?
.filter(someObject -> (if(string != null) someobject.getName == string))
// The second problem is to collect custom map like
.collect(Collectors.toMap("customField1"), someObject.getName()) ... // I need somehow put some additional custom fields here
}
現在我正在收集這樣的自定義地圖:
Map<String, Object> someMap = new LinkedHashMap<>();
someMap.put("someCustomField1", someObject.field1());
someMap.put("someCustomField2", someObject.field2());
someMap.put("someCustomField3", someObject.field3());
只需檢查是否需要應用過濾器,然后使用filter
方法或不使用它:
protected List<Map<String, Object>> populate(List<SomeObject> someObjects, String string) {
Stream<SomeObject> stream = someObjects.stream();
if (string != null) {
stream = stream.filter(s -> string.equals(s.getName()));
}
return stream.map(someObject -> {
Map<String, Object> map = new LinkedHashMap<>();
map.put("someCustomField1", someObject.Field1());
map.put("someCustomField2", someObject.Field2());
map.put("someCustomField3", someObject.Field3());
return map;
}).collect(Collectors.toList());
}
試試這個:
protected List<Map<String, Object>> populate(List<SomeObject> someObjects, String string) {
return someObjects.stream()
.filter(someObject -> string == null || string.equals(someObject.getName()))
.map(someObject ->
new HashMap<String, Object>(){{
put("someCustomField1", someObject.Field1());
put("someCustomField2", someObject.Field2());
put("someCustomField3", someObject.Field3());
}})
.collect(Collectors.toList()) ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.