I have the following code:
public boolean foo(List<JSONObject> source, String bar, String baz) {
List<String> myList = newArrayList();
source.forEach(json -> {
if (!(json.get(bar) instanceof JSONObject)) {
myList.add(json.get(bar).toString());
} else {
myList.add(json.getJSONObject(attribute).get("key").toString());
}
});
/**
* do something with myList and baz
*/
}
I'm just wondering if there's a way to do the if-else condition inline using a filter.
Something along the lines of:
List<String> myList = source.stream()
.filter(json -> !(json.get(bar) instanceof JSONObject))
.map(item -> item.get(attribute).toString())
.collect(Collectors.toList());
If I go by the approach above, I will miss the supposed to be "else" condition. How can I achieve what I want using a more java-8 way?
Thanks in advance!
if-elseto the map operation, but it would just get unreadable. Java8 is not always the best approach, why not just use the simple old iterative way?