猿问

如何使用 java 流过滤 List<String,Object> 集合?

我有


List<String, Person> generalList

作为一个列表。在 Person 下有 Customer 对象,在 Customer 下还有 1 个列表,名为 Id


我想在对象下过滤这个嵌套的 IdList 但它不起作用。


我尝试使用 flatMap 但此代码不起作用


String s = generalList.stream()

.flatMap(a -> a.getCustomer().getIdList().stream())

.filter(b -> b.getValue().equals("1"))

.findFirst()

.orElse(null);

我希望输出为 String 或 Customer 对象


编辑:我的原始容器是地图,我正在过滤 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*/

}

和身份证


public class Id {

private String value;

/*getter setter*/

}


qq_笑_17
浏览 275回答 2
2回答

智慧大石

您可能正在寻找以下map操作:String&nbsp;s&nbsp;=&nbsp;list.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.flatMap(a&nbsp;->&nbsp;a.getCustomer().getIdList().stream()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(b&nbsp;->&nbsp;b.getValue().equals("1")) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.findFirst() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(Id::getValue)&nbsp;//&nbsp;map&nbsp;to&nbsp;the&nbsp;value&nbsp;of&nbsp;filtered&nbsp;Id &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.orElse(null);这相当于(只是为了澄清)String&nbsp;valueToMatch&nbsp;=&nbsp;"1";String&nbsp;s&nbsp;=&nbsp;list.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.flatMap(a&nbsp;->&nbsp;a.getCustomer().getIdList().stream()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.anyMatch(b&nbsp;->&nbsp;b.getValue().equals(valueToMatch)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;?&nbsp;valueToMatch&nbsp;:&nbsp;null;

呼唤远方

更新 2此解决方案直接适用于 Person 对象列表:String key = "1";List<Person> list = container.get("A");String filteredValue = list.stream()&nbsp; &nbsp; .flatMap(person -> Arrays.stream(person.getCustomer().getId())&nbsp; &nbsp; .filter(id -> id.getValue().equals(key)))&nbsp; &nbsp; .findFirst().get().getValue();使用地图的旧答案由于您只对地图的值感兴趣,因此您应该对它们进行流式传输,而在 flatMap 中,我不仅在getId()列表中获得了流,而且还直接对其进行了过滤。因此,如果我正确理解了您的代码结构,这应该可以String key = "1";&nbsp;String filteredValue =&nbsp; map.values().stream()&nbsp; &nbsp; &nbsp;.flatMap(list -> list.stream()&nbsp; &nbsp; &nbsp;.flatMap(person -> Arrays.stream(person.getCustomer().getId())&nbsp; &nbsp; &nbsp;.filter(id -> id.getValue().equals("1"))))&nbsp; &nbsp; &nbsp;.findFirst().get().getValue();更新以调整已编辑的问题
随时随地看视频慕课网APP

相关分类

Java
我要回答