Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8: Filter and map on same method output

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?

like image 728
Amit Dalal Avatar asked Aug 24 '16 12:08

Amit Dalal


People also ask

Can we use map and filter together in Java 8?

With Java 8, you can convert a Map. entrySet() into a stream , follow by a filter() and collect() it.

Can we use filter and map together in Java?

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.

What is the difference between map and filter in Java 8?

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.

How do I filter a map based on values in Java 8?

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.


1 Answers

Well you can do the filtering after the mapping step:

x.stream()
  .map(s -> m(s.getKey()))
  .filter(Objects::nonNull)
  .collect(Collectors.toList());
like image 102
Flown Avatar answered Oct 18 '22 09:10

Flown