Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 293
Himanshu Yadav Avatar asked Dec 11 '22 07:12

Himanshu Yadav


1 Answers

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())
like image 67
fps Avatar answered Dec 29 '22 02:12

fps