简体   繁体   English

从List中提取值(而不是键) <Map<String,String> &gt;,并将其展平为List <String>

[英]Extract values (not keys) from a List<Map<String,String>>, and flatten it to a List<String>

How would I extract the values (not keys) from a List<Map<String,String>> , and flatten it to a List<String> ? 如何从List<Map<String,String>>提取值(而不是键),并将其展平为List<String>

ie tried the following but doesn't work. 即尝试以下但不起作用。

List<Map<String,String>> mapList = .... ;

List<String> valueList = mapList.stream()
                                .map(o -> o.getValue())
                                .collect(Collectors.toList());

I'd like to filter the result by a given key as well. 我想用给定的键过滤结果。

You mean : 你的意思是 :

List<String> valueList = mapList.stream()
        .flatMap(a -> a.values().stream())
        .collect(Collectors.toList());

Edit 编辑

What if I want to specify a key eg I have "id" and "firstName", but only want "firstName" 如果我想指定一个键,例如我有“id”和“firstName”,但只想要“firstName”,该怎么办?

In this case you can use filter after the flatmap like so : 在这种情况下,您可以在flatmap之后使用filterflatmap所示:

List<String> valueList = mapList.stream()
        .flatMap(a -> a.entrySet().stream())
        .filter (e -> e.getKey().equals("firstName"))
        .map(Map.Entry::getValue)
        .collect(Collectors.toList ());

Use .flatMap : 使用.flatMap

List<Map<String,String>> mapList = new ArrayList<>();

Map<String, String> mapOne = new HashMap<>();
mapOne.put("1", "one");
mapOne.put("2", "two");

Map<String, String> mapTwo = new HashMap<>();
mapTwo.put("3", "three");
mapTwo.put("4", "four");

mapList.add(mapOne);
mapList.add(mapTwo);

List<String> allValues = mapList.stream()
    .flatMap(m -> m.values().stream())
    .collect(Collectors.toList()); // [one, two, three, four]

Try 尝试

    List<String> valueList = mapList.stream()
            .flatMap(map -> map.entrySet().stream())
            .filter(entry -> entry.getKey().equals("KEY"))
            .map(Map.Entry::getValue)
            .collect(Collectors.toList());

The object o you are trying to map to o.getValue() is of type Map (which does not have a function getValue()), not Map.Entry (which would have such a function). 您尝试映射到o.getValue()的对象是Map类型(它没有函数getValue()),而不是Map.Entry(它具有这样的函数)。 What you can is get a Collection of the values with the function o.values(). 你可以通过函数o.values()得到值的集合。

You can then get a Stream from that collection, and flatten the resulting Stream of Streams like this: 然后,您可以从该集合中获取Stream,并将生成的Streams流平整为:

List<String> valueList = mapList.stream()
                         .map(o -> o.values().stream())
                         .flatMap(Function.identity())
                         .collect(Collectors.toList());

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

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