Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter null values after map in Java 8 [duplicate]

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?

like image 294
cybertextron Avatar asked Nov 24 '16 04:11

cybertextron


People also ask

How do I filter null values in Java 8?

Java 8 Example: Filter null values from a stream We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.

Can collectors toMap return null?

toMap throws a NullPointerException if one of the values is null .

How do I check if a map is empty or null in Java 8?

util. HashMap. isEmpty() method of HashMap class is used to check for the emptiness of the map. The method returns True if no key-value pair or mapping is present in the map else False.

Can we use map after filter in Java 8?

With Java 8, you can convert a Map. entrySet() into a stream , follow by a filter() and collect() it.


1 Answers

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());
like image 52
Zbynek Vyskovsky - kvr000 Avatar answered Oct 13 '22 11:10

Zbynek Vyskovsky - kvr000