Reputation: 7127
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());
Upvotes: 6
Views: 9066
Reputation: 82521
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());
}
Upvotes: 9
Reputation: 5068
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()) ;
}
Upvotes: 4