【问题标题】:Filter null values after map in Java 8 [duplicate]在 Java 8 中的映射后过滤空值 [重复]
【发布时间】:2017-04-08 06:06:05
【问题描述】:

我是在 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。如何在map 之后过滤(删除)null LabeledPoint 对象?

【问题讨论】:

    标签: java filter java-8 java-stream


    【解决方案1】:

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

    【讨论】:

    • 你也可以使用.filter(Objects::nonNull)
    猜你喜欢
    • 2018-01-01
    • 2014-06-06
    • 1970-01-01
    • 2019-01-08
    • 2018-08-08
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2021-09-13
    相关资源
    最近更新 更多