We are trying to refactor below code to java 8:
List<String> list = new ArrayList<>();
Iterator<Obj> i = x.iterator();
while (i.hasNext()) {
String y = m(i.next().getKey());
if (y != null) {
list.add(y);
}
}
return list;
So far we have come up with:
return x.stream()
.filter(s -> m(s.getKey()) != null)
.map(t -> m(t.getKey()))
.collect(Collectors.toList());
But the method m()
is being invoked twice here. Is there any way around?
With Java 8, you can convert a Map. entrySet() into a stream , follow by a filter() and collect() it.
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.
Filter takes a predicate as an argument so basically you are validating your input/collection against a condition, whereas a map allows you to define or use a existing function on the stream eg you can apply String.
We can filter a Map in Java 8 by converting the map. entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.
Well you can do the filtering after the mapping step:
x.stream()
.map(s -> m(s.getKey()))
.filter(Objects::nonNull)
.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