nullpointerexception - Dealing with a null attribute using java 8 streams and sorting using lambda expressions -
let's consider parent class contains 1 integer attribute. created 6 objects of parent class , values of attribute 100, 20, 300, 400, 500, null.
now added objects list(name of list list). want objects attribute value greater 100. used java 8 streams purpose.
predicate<entity> predicate = e -> e.getparentid() < 100; result = list.stream().filter(predicate).collect(collectors.tolist()); i want sort list in descending order. used following code purpose.
comparator<entity> comp = (d1,d2) -> d2.getid().compareto(d1.getid()); list.sort(comp); in both cases nullpointerexception.
how handle this?
all of answers here revolve around "throw out bad elements, have null getparentid()." may answer, if indeed bad. there's alternative: comparators.nullsfirst (or last.) allows compare things treating null value being less (or greater than) non-null values, don't have throw elements null parentid away.
comparator<entity> cmp = nullslast(comparing(entity::getparentid)); list<entity> list = list.stream().sorted(cmp).collect(tolist()); you can similar thing filtering; define predicate as:
predicate<entity> predicate = e -> e.getparentid() != null && e.getparentid() < 100;
Comments
Post a Comment