在Java 8中映射后过滤空值

时间:2016-11-24 04:04:07

标签: java filter java-8 java-stream

我在Java 8中使用mapfilters的新用户。我目前正在使用Spark ML库来处理某些ML算法。 我有以下代码:

// return a list of `Points`.
List<Points> points = getPoints();
List<LabeledPoint> labeledPoints = points.stream()
                                        .map(point -> getLabeledPoint(point))
                                        .collect(Collectors.toList());

如果数据正确,函数getLabeledPoint(Point point)将返回新的LabeledPoint,否则返回null。如何在null之后过滤(删除)LabeledPoint map个对象?

1 个答案:

答案 0 :(得分:14)

Stream上有filter方法:

// 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());