Java 8使用条件过滤并收集自定义Map

J-A*_*lex 6 java lambda filter java-8 java-stream

我有一些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
}
Run Code Online (Sandbox Code Playgroud)

现在我正在收集这样的自定义地图:

Map<String, Object> someMap = new LinkedHashMap<>();
someMap.put("someCustomField1", someObject.field1());
someMap.put("someCustomField2", someObject.field2());
someMap.put("someCustomField3", someObject.field3());
Run Code Online (Sandbox Code Playgroud)

fab*_*ian 9

只需检查是否需要应用过滤器然后使用该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());
}
Run Code Online (Sandbox Code Playgroud)