在Java 8中映射后过滤空值

cyb*_*ron 8 java filter java-8 java-stream

我是Java mapfilters8中的新用户.我目前正在使用Spark ML库来进行一些ML算法.我有以下代码:

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

如果数据正确,则函数getLabeledPoint(Point point)返回new,LabeledPoint否则返回null.我怎样才能过滤(删除)null LabeledPoint对象map

Zby*_*000 19

filterStream上有方法:

// 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());
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用`.filter(Objects :: nonNull)` (28认同)