Java 8 Stream API 查找与属性值匹配的唯一对象 [英] Java 8 Stream API to find Unique Object matching a property value

查看:33
本文介绍了Java 8 Stream API 查找与属性值匹配的唯一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Java 8 Stream 从集合中查找与属性值匹配的对象.

Find the object matching with a Property value from a Collection using Java 8 Stream.

List<Person> objects = new ArrayList<>();

人员属性 -> 姓名、电话、电子邮件.

Person attributes -> Name, Phone, Email.

遍历人员列表并找到与电子邮件匹配的对象.看到这可以通过 Java 8 流轻松完成.但这仍然会返回一个集合?

Iterate through list of Persons and find object matching email. Saw that this can be done through Java 8 stream easily. But that will still return a collection?

例如:

List<Person> matchingObjects = objects.stream.
    filter(p -> p.email().equals("testemail")).
    collect(Collectors.toList());

但我知道它总会有一个独特的对象.我们可以做些什么来代替 Collectors.toList 以便我直接得到实际的对象.而不是获取对象列表.

But I know that it will always have one unique object. Can we do something instead of Collectors.toList so that i got the actual object directly.Instead of getting the list of objects.

推荐答案

尝试使用 findFirstfindAny 代替收集器.

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

这将返回一个 Optional,因为列表可能不包含该对象.

This returns an Optional since the list might not contain that object.

如果您确定列表中始终包含您可以致电的人:

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

但要小心! get 如果不存在任何值,则抛出 NoSuchElementException.因此强烈建议您首先确保该值存在(使用 isPresent 或更好,使用 ifPresentmaporElseOptional 类中的任何其他替代方案).

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

如果你对 null 引用没问题,如果没有这样的人,那么:

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

如果可能,我会尽量避免使用 null 参考路线.Optional 类中的其他替代方法(ifPresentmap 等)可以解决许多用例.我发现自己使用 orElse(null) 的地方只有当我现有的代码被设计为在某些情况下接受 null 引用时.

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.

Optionals 还有其他有用的方法.看看可选javadoc.

Optionals have other useful methods as well. Take a look at Optional javadoc.

这篇关于Java 8 Stream API 查找与属性值匹配的唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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