在使用lambda表达式排序之前检查null值 [英] check null value before sorting using lambda expression

查看:632
本文介绍了在使用lambda表达式排序之前检查null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用lambda表达式对parentId进行menuList排序,parentId可以为null。我尝试下面的代码,但我无法找到为parentId添加nullcheck的方法,因为我得到nullpointer异常。

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()));

你能否帮助我为parentId添加nullcheck。
注意:我不想跳过parentId为null的菜单。

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

推荐答案

在Comparator中使用工厂方法:

Use the factory methods in Comparator:

menuList.sort(Comparator.comparing(MenuList::getParentId, Comparator.nullsLast(Comparator.naturalOrder())));

这篇关于在使用lambda表达式排序之前检查null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆