Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check null value before sorting using lambda expression

Tags:

lambda

java-8

I want to sort the menuList by parentId using lambda expression, parentId can be null. i tried below code but i am not able to find the way to add nullcheck for parentId, because of which i am getting nullpointer exception.

List<MenuList> menuList = session.createQuery("from MenuList").list();
menuList.sort((p1, p2) ->
p1.getParentId().compareTo(p2.getParentId()));

could you help me in adding nullcheck for parentId. Note: I don't want to skip the menu having parentId null.

like image 501
Abhijit Avatar asked Sep 18 '15 18:09

Abhijit


1 Answers

Use the factory methods in Comparator:

menuList.sort(Comparator.comparing(MenuList::getParentId, Comparator.nullsLast(Comparator.naturalOrder())));
like image 166
JB Nizet Avatar answered Oct 12 '22 02:10

JB Nizet