'How to avoid NPE in below case?

List<User> sortedList = userList.stream()       
    .sorted(Comparator.comparingInt(User::getAge).reversed())
    .collect(Collectors.toList());

sortedList.forEach(System.out::println)

In the above case if User is null it is giving NPE. How to avoid NPE here?



Solution 1:[1]

Yes I got the solution. It is very easy. Just use stream. filter(a->a!=null)...

List<User> sortedList = userList.stream()
    .filter(a->a!=null)       
    .sorted(Comparator.comparingInt(User::getAge).reversed())
    .collect(Collectors.toList());

sortedList.forEach(System.out::println)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stewart