在 Java 8 中映射后过滤空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40777874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:27:50  来源:igfitidea点击:

Filter null values after map in Java 8

javafilterjava-8java-stream

提问by cybertextron

I'm new in using mapand filtersin Java 8. I'm currently using Spark MLlibrary for some ML algorithms. I have the following code:

我在使用新的mapfilters在Java中8.我目前使用的Spark ML库对于一些ML算法。我有以下代码:

// 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 LabeledPointif the data is correct or null otherwise. How can I filter (remove) the nullLabeledPointobjects after map?

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

回答by Zbynek Vyskovsky - kvr000

There is filtermethod on Stream:

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