java - 使用流从 Map 对象列表中仅获取键

标签 java dictionary collections java-8 java-stream

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

当我流式传输 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对象?

最佳答案

您可以在每个 MapkeySet 上使用 flatMap:

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

关于java - 使用流从 Map 对象列表中仅获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59835334/

相关文章:

java - 使用 Hadoop 分布式缓存的问题

python - 在 Python 字典中如何根据键的第一个值找到一个?

python - 二维字典或其他键顺序无关紧要的数据结构

c# - 结合 ConcurrentQueue 和 ConcurrentStack

java - 未设置Nutch 1.11 JAVA_HOME错误。

java - C# 服务器、Android Java 客户端 - 连接问题

python 字典: get vs setdefault

java - 从 Iterator<T> 创建 List<T> 实例

Java 8 使用 stream() 将 List<Object> 提取/转换为 Map<String, List<String>>

java - 获取所有给定列表中出现的所有字符串