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

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

问题描述

使用Java 8 Stream从Collection中查找与Property值匹配的对象。

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?

Ex:

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.

推荐答案

尝试使用 findFirst 或<$ c而不是使用收集器$ c> findAny 。

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

这会返回可选,因为列表可能会不包含该对象。

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

如果您不确定并希望获得 null 如果没有这样的人,那么:

If you aren't sure and want to get null if there is no such person, then:

Person person = matchingObject.orElse(null);






Optionals还有其他有用的方法。请查看可选的javadoc

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

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