-1
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?

Stewart
  • 17,616
  • 8
  • 52
  • 80
  • 1
    What should the result be when `AnyObj` is null? How should those values compare to others in the list? – Karl Knechtel May 13 '22 at 14:14
  • Also: consider whether there is a good reason to allow null values to exist in the list in the first place. – Karl Knechtel May 13 '22 at 14:16
  • 1
    Is this really valid syntax for a comparator lambda? – GhostCat May 13 '22 at 14:16
  • Maybe this answer helps you: https://stackoverflow.com/questions/32884195/filter-values-only-if-not-null-using-lambda-in-java8 - you can filter the null values in the list before sorting it – Jelmen May 13 '22 at 14:17
  • 1
    @GhostCat I haven't used Java in a long time and had to look up the new features; but I'm pretty sure that's meant to be either `AnyObj -> AnyObj.getAttr()`, or `AnyObj::getAttr`. – Karl Knechtel May 13 '22 at 14:18
  • 1
    I agree with Karl ... this really doesn't look like valid Java syntax. Please: be diligent about your input. You want other people to spend their free time to help you with your problem for free. So please spend the 1 minute it takes to show us REAL legit java code, not something "pseudo" that you BELIEVE communicates your intent. – GhostCat May 13 '22 at 14:20
  • And yes, nulls can be filtered out before ... but the question is: is that what the OP wants?! So the real question is something only the OP can answer: what are the requirements. Why are there nulls in the list, and more importantly, how should sorting affect those null values? – GhostCat May 13 '22 at 14:21

1 Answers1

0

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)
Stewart
  • 17,616
  • 8
  • 52
  • 80