Filter null values after map in Java 8 [duplicate]

感情迁移 提交于 2020-11-28 04:40:49

问题


I'm new in using map and filters in Java 8. I'm currently using Spark ML library for some ML algorithms. I have the following code:

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


回答1:


There is filter method on Stream:

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


来源:https://stackoverflow.com/questions/40777874/filter-null-values-after-map-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!