Java 8 Filtering with condition and collecting custom Map
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()) ;
}