简体   繁体   English

Java 8:如何从列表中的 object 中获取属性,其中 object 的其他属性必须与输入匹配

[英]Java 8: How get a property from an object in a list where the other property of object must match with input

class Person{
     String Name;
     String Id;
    }

I have a list of person.我有一个人的名单。 I want to get the id of a person where the Name matches with input, I know it can be done by using filter but in my case, name is always unique so I get only one ID back.我想获取名称与输入匹配的人的 ID,我知道可以通过使用过滤器来完成,但在我的情况下,名称始终是唯一的,所以我只得到一个 ID。 Please let me know if there is any other efficient ways to do this.如果有任何其他有效的方法可以做到这一点,请告诉我。

If you are going to query on name many times you could keep a map around that maps a Person to a name (and that's assuming your names are indeed unique).如果您要多次查询名称,您可以在周围保留一个 map 将一个人映射到一个名称(假设您的名称确实是唯一的)。

Map<String, Person> byName = new HashMap<>();
yourList.forEach(person -> byName.put(person.name, person));

and then lookup the person directly by name:然后直接按姓名查找此人:

Person person = byName.get("a name");
if (person != null) {
...
}

Since the name is unique, you could use the short-circuiting terminal operation findFirst after the filter .由于名称是唯一的,您可以在filter之后使用短路终端操作findFirst This would allow the stream processing to stop as soon as a match is encountered.这将允许 stream 处理在遇到匹配时立即停止。

return list.stream()
           .filter(p -> p.getName().equals(input))
           .findFirst() // Optional<Person> is returned
           .map(Person::getId)
           .orElse(null);// if no matching name is found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM