Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with a null attribute using java 8 streams and sorting using lambda expressions

Let's consider a Parent class which contains only one Integer attribute. I created 6 objects of parent class and values of attribute are 100, 20, 300, 400, 500, null.

Now I added all the objects to a list(Name of list is list). Then I want to get the objects whose attribute value is greater than 100. I used Java 8 streams for this purpose.

Predicate<Entity> predicate = e -> e.getParentId() < 100;
result = list.stream().filter(predicate).collect(Collectors.toList());

I also want to sort the list in descending order. I used the following code for this purpose.

Comparator<Entity> comp = (d1,d2) -> d2.getId().compareTo(d1.getId());
list.sort(comp);

In both cases I get a NullPointerException.

How to handle this?

like image 548
Manu Joy Avatar asked Jul 08 '15 05:07

Manu Joy


1 Answers

All of the answers here revolve around "throw out the bad elements, those that have a null getParentId()." That may be the answer, if they are indeed bad. But there's another alternative: Comparators.nullsFirst (or last.) This allows you to compare things treating a null value as being less than (or greater than) all non-null values, so you don't have to throw the elements with a null parentId away.

Comparator<Entity> cmp = nullsLast(comparing(Entity::getParentId));
List<Entity> list = list.stream().sorted(cmp).collect(toList());

You can do a similar thing for filtering; define your predicate as:

Predicate<Entity> predicate = e -> e.getParentId() != null 
                                       && e.getParentId() < 100;
like image 137
Brian Goetz Avatar answered Sep 19 '22 21:09

Brian Goetz