繁体   English   中英

如何筛选清单 <String,Object> 用Java流收集吗?

[英]How to Filter List<String,Object> Collection with java stream?

我有

List<String, Person> generalList

作为列表。 在“个人”下有“客户”对象,在“客户”下还有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<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操作,例如:

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;

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

使用map的旧答案因为您只对map的值感兴趣,所以应该在它们上进行流传输,在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();

更新以适应已编辑的问题

暂无
暂无

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

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