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
?
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.
toMap throws a NullPointerException if one of the values is null .
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.
With Java 8, you can convert a Map. entrySet() into a stream , follow by a filter() and collect() it.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With