Himanshu Yadav
Himanshu Yadav

Reputation: 13587

Java 8 streams: Handle null values

Following code is throwing NPE for the property Salary being null. class Person has properties: string: name, Integer: age, Integer: salary salary can be null here. I want to create a List of salaries.

persons.stream().mapToDouble(Person::getSalary).boxed().collect(Collectors.toList())
Here I must retain null values in the result list. null can not be replaced with 0.

Upvotes: 5

Views: 8479

Answers (2)

fps
fps

Reputation: 34460

I think you could use map instead of mapToDouble along with the ternary operator:

List<Double> salaries = persons.stream()
    .map(Person::getSalary)
    .map(s -> s == null ? null : s.doubleValue())
    .collect(Collectors.toList())

Upvotes: 11

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

If I understand correctly, you want to convert each property value to Double if it's non-null, or leave it as null if it's null. So just say so:

Integer prop = value.getProperty();
return (prop != null) ? prop.doubleValue() : null;

You can express that as a lambda, and pass it to map(). (Left as an exercise for the reader.)

Upvotes: 3

Related Questions