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!
That's all about how to use map and filter in Java 8. We have seen an interesting example of how we can use the map to transform an object to another and how to use filter to select an object based upon condition. We have also learned how to compose operations on stream to write code that is both clear and concise.
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
2. Java stream filter multiple conditions. One of the utility method filter() helps to filter the stream elements based on a given predicate. The predicate is a functional interface that takes a single element as an argument and evaluates it against a specified condition).
The only way I see is putting the condition in the map
call. If you use filter
you lose the "else" part.
List<String> myList = source.stream()
.map(item -> {
if (!(item.get(bar) instanceof JSONObject)) {
return item.get(bar).toString();
} else {
return item.getJSONObject(attribute).get("key").toString();
}
})
.collect(Collectors.toList());
or, as Holger suggested in a comment, use the ternary conditional operator:
List<String> myList = source.stream()
.map(i -> (i.get(bar) instanceof JSONObject ? i.getJSONObject(attribute).get("key") : i.get(bar)).toString())
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With