我有一些集合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());
答案 0 :(得分:4)
试试这个:
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()) ;
}