Java-8 – Java 8: filtering and mapping on the same method output
•
Java
We try to refactor the following code into 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 proposed:
return x.stream().filter(s -> m(s.getKey()) != null).map(t -> m(t.getKey())).collect(Collectors.toList());
But the method m () is called twice here Is there any way?
Solution
Then you can filter after the mapping step:
x.stream().map(s -> m(s.getKey())).filter(Objects::nonNull).collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
