[英]How to Filter List<String,Object> Collection with java stream?
I have 我有
List<String, Person> generalList
as a list. 作为列表。 there is Customer object Under Person, 1 more list under Customer named Id 在“个人”下有“客户”对象,在“客户”下还有1个名为“ Id”的列表
I want to filter this nested IdList under object but it is not working. 我想过滤此嵌套的IdList对象下,但它不起作用。
I tried to use flatMap but this code is not working 我尝试使用flatMap,但是此代码无法正常工作
String s = generalList.stream()
.flatMap(a -> a.getCustomer().getIdList().stream())
.filter(b -> b.getValue().equals("1"))
.findFirst()
.orElse(null);
I expect the output as String or Customer object 我希望输出为String或Customer对象
Edit: My original container is a map, I am filtering Map to List 编辑:我原来的容器是一个地图,我正在筛选地图到列表
Explanation. 说明。
Map<String, List<Person> container;
List<Person> list = container.get("A");
String s = list.stream()
.flatMap(a -> a.getCustomer().getIdList().stream())
.filter(b -> b.getValue().equals("1"))
.findFirst()
.orElse(null);
Here is the Person 这是人
public class Person
{
private Customer customer;
public Customer getCustomer ()
{
return customer;
}
}
And Customer 和客户
public class Customer {
private Id[] idList;
/*getter setter*/
}
And Id 和ID
public class Id {
private String value;
/*getter setter*/
}
You're possibly looking for a map
operation as: 您可能正在寻找map
操作,例如:
String s = list.stream()
.flatMap(a -> a.getCustomer().getIdList().stream())
.filter(b -> b.getValue().equals("1"))
.findFirst()
.map(Id::getValue) // map to the value of filtered Id
.orElse(null);
which is equivalent of(just to clarify) 等价于(仅作澄清)
String valueToMatch = "1";
String s = list.stream()
.flatMap(a -> a.getCustomer().getIdList().stream())
.anyMatch(b -> b.getValue().equals(valueToMatch))
? valueToMatch : null;
Update 2 This solution works directly on a list of Person objects: 更新2此解决方案直接在Person对象的列表上起作用:
String key = "1";
List<Person> list = container.get("A");
String filteredValue = list.stream()
.flatMap(person -> Arrays.stream(person.getCustomer().getId())
.filter(id -> id.getValue().equals(key)))
.findFirst().get().getValue();
Old answer working with map Since you are only interested in the values of your map you should stream on them and in the flatMap I not only got a stream on the getId()
list but also filtered on them directly. 使用map的旧答案因为您只对map的值感兴趣,所以应该在它们上进行流传输,在flatMap中,我不仅在getId()
列表上获得了流,还直接对其进行了过滤。 So if I understood your code structure correctly this should work 因此,如果我正确理解了您的代码结构,这应该可以工作
String key = "1";
String filteredValue = map.values().stream()
.flatMap(list -> list.stream()
.flatMap(person -> Arrays.stream(person.getCustomer().getId())
.filter(id -> id.getValue().equals("1"))))
.findFirst().get().getValue();
Updated to adjust for edited question 更新以适应已编辑的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.