问题
I'm new in using map
and filters
in Java 8. I'm currently using Spark ML
library for some ML algorithms.
I have the following code:
// return a list of `Points`.
List<Points> points = getPoints();
List<LabeledPoint> labeledPoints = points.stream()
.map(point -> getLabeledPoint(point))
.collect(Collectors.toList());
The function getLabeledPoint(Point point)
returns a new LabeledPoint
if the data is correct or null otherwise. How can I filter (remove) the null
LabeledPoint
objects after map
?
回答1:
There is filter method on Stream:
// return a list of `Points`.
List<Points> points = getPoints();
List<LabeledPoint> labeledPoints = points.stream()
.map(point -> getLabeledPoint(point))
// NOTE the following:
.filter(e -> e != null)
.collect(Collectors.toList());
来源:https://stackoverflow.com/questions/40777874/filter-null-values-after-map-in-java-8