简体   繁体   中英

Java 8 Filtering with condition and collecting custom Map

I have some collection List<Map<String, Object>> which need to be filtered optionally with Java 8 lambda expressions. I will receive JSON object with flags which filtering criteria have to be applied. If JSON object is not received, then no filtering is needed.

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
}

Now I'm collecting custom map like that:

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

Just check, whether you need to apply the filter or not and then use the filter method or don't use it:

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());
}

Try with this:

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()) ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM