使用 java 8 流处理空属性并使用 lambda 表达式进行排序 [英] Dealing with a null attribute using java 8 streams and sorting using lambda expressions

查看:20
本文介绍了使用 java 8 流处理空属性并使用 lambda 表达式进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一个 Parent 类,它只包含一个 Integer 属性.我创建了父类的 6 个对象,属性值分别为 100、20、300、400、500、null.

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.

现在我将所有对象添加到列表中(列表名称为列表).然后我想获取属性值大于100的对象.为此,我使用了 Java 8 流.

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

在这两种情况下,我都会收到 NullPointerException.

In both cases I get a NullPointerException.

如何处理?

推荐答案

看起来您正在寻找以下内容:

Looks like you are looking for something like:

list.sort(Comparator.comparing(Entity::getParent, 
                               Comparator.nullsLast(Integer::compareTo)));

所有父元素为 null 的元素将放在最后,其余元素将按其父元素排序.

All the elements with parent null will be put at the end and the rest will be sorted by their parent.

这篇关于使用 java 8 流处理空属性并使用 lambda 表达式进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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