在Java 8中进行map操作后过滤空值

21

我刚开始使用Java 8中的mapfilters。目前我正在使用Spark 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。如何在 map 后过滤(删除)nullLabeledPoint 对象?

1个回答

38

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

58
你可以使用 .filter(Objects::nonNull)。意思是筛选掉值为 null 的元素。 - Mikhail

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接