如何过滤列表< String,Object>用Java流收集吗? [英] How to Filter List<String,Object> Collection with java stream?
本文介绍了如何过滤列表< String,Object>用Java流收集吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
List<String, Person> generalList
作为列表.在人员"下有一个客户"对象,在客户"下还有1个名为ID的列表
as a list. there is Customer object Under Person, 1 more list under Customer named Id
我想在对象下过滤此嵌套的IdList,但它不起作用.
I want to filter this nested IdList under object but it is not working.
我尝试使用flatMap,但是此代码无法正常工作
I tried to use flatMap but this code is not working
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
我原来的容器是地图,我正在过滤地图到列表"
My original container is a map, I am filtering Map to List
说明.
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);
这里是人
public class Person
{
private Customer customer;
public Customer getCustomer ()
{
return customer;
}
}
和客户
public class Customer {
private Id[] idList;
/*getter setter*/
}
和ID
public class Id {
private String value;
/*getter setter*/
}
推荐答案
您可能正在寻找 map
操作,如下所示:
You're possibly looking for a map
operation as:
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);
等同于(为澄清起见)
String valueToMatch = "1";
String s = list.stream()
.flatMap(a -> a.getCustomer().getIdList().stream())
.anyMatch(b -> b.getValue().equals(valueToMatch))
? valueToMatch : null;
这篇关于如何过滤列表< String,Object>用Java流收集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文