21

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?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
cybertextron
  • 10,547
  • 28
  • 104
  • 208

1 Answers1

38

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());
Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43