2016-11-24 47 views
1

我是在Java 8中使用mapfilters的新功能。我目前对某些ML算法使用Spark ML库。 我有以下代码:在Java 8中映射后过滤空值

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

如果数据是正确的;否则为null getLabeledPoint(Point point)返回一个新LabeledPoint功能。如何过滤(删除)map后的对象?

回答

8

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

你也可以用'.filter(对象::非空)' – Mikhail