【问题标题】:Get only key from List of Map object using stream使用流从 Map 对象列表中仅获取键
【发布时间】:2020-05-07 04:10:11
【问题描述】:

我正在尝试使用 java 8 中的流从 Map 对象列表中仅获取键值。

当我流式传输地图对象列表时,我得到的是 Stream<List<String>> 而不是 List<String>

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamTest {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Hello World");
    Map<String, String> a = new HashMap<String, String>();
    a.put("1", "Bharathi");
    a.put("2", "Test");
    a.put("3", "Hello");
    List<Map<String, String>> b = new ArrayList<>();
    b.add(a);
    System.out.println("Hello World" + b);

    /*
     * b.stream().map(c-> c.entrySet().stream().collect( Collectors.toMap(entry ->
     * entry.getKey(), entry -> entry.getValue())));
     */

    Stream<List<String>> map2 = b.stream()
            .map(c -> c.entrySet().stream().map(map -> map.getKey()).collect(Collectors.toList()));
    //List<List<String>> collect = map2.map(v -> v).collect(Collectors.toList());

  }

}

如何从Map对象的List中获取key对象?

【问题讨论】:

    标签: java dictionary collections java-8 java-stream


    【解决方案1】:

    您也可以使用稍微声明性的方式:

    List<String> collect = b.stream()
                    .map(Map::keySet) // map maps to key sets
                    .flatMap(Collection::stream) // union all key sets to the one stream
                    .collect(Collectors.toList()); // collect the stream to a new list
    

    【讨论】:

      【解决方案2】:

      当然flatMap 是基于流的解决方案!但是,您可以以简单的方式使用非流版本进行操作。

      List<String> map2 = new ArrayList<>();
      b.forEach(map -> map2.addAll(map.keySet()));
      

      【讨论】:

        【解决方案3】:

        您可以在每个Map 内的keySet 上使用flatMap

        List<String> output = lst.stream()
                    .flatMap(mp -> mp.keySet().stream())
                    .collect(Collectors.toList());
        

        【讨论】:

        • 旁白:将对象建模为List&lt;Map&lt;String, String&gt;&gt; 而不是自定义类,然后进一步使用List&lt;CustomClass&gt;,并没有太多好处。
        【解决方案4】:

        你可以简单地flatMap它:

        b.stream().flatMap(m -> m.keySet().stream()).collect(Collectors.toList())
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-13
          • 2015-02-13
          • 2020-10-10
          • 1970-01-01
          • 2020-08-29
          • 2019-08-02
          相关资源
          最近更新 更多