为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_笑_17 2022-06-04 16:40:16
我有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*/}
查看完整描述

2 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

您可能正在寻找以下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);

这相当于(只是为了澄清)

String valueToMatch = "1";String s = list.stream()
        .flatMap(a -> a.getCustomer().getIdList().stream())
        .anyMatch(b -> b.getValue().equals(valueToMatch))
        ? valueToMatch : null;


查看完整回答
反对 回复 2022-06-04
?
呼唤远方

TA贡献1856条经验 获得超11个赞

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

使用地图的旧答案由于您只对地图的值感兴趣,因此您应该对它们进行流式传输,而在 flatMap 中,我不仅在getId()列表中获得了流,而且还直接对其进行了过滤。因此,如果我正确理解了您的代码结构,这应该可以


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

更新以调整已编辑的问题


查看完整回答
反对 回复 2022-06-04
  • 2 回答
  • 0 关注
  • 274 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号