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

bha*_*thi 3 java collections dictionary java-8 java-stream

我正在尝试使用 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());

  }

}
Run Code Online (Sandbox Code Playgroud)

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

Nam*_*man 5

您可以使用flatMapoverkeySet每个Map内的:

List<String> output = lst.stream()
            .flatMap(mp -> mp.keySet().stream())
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

  • 旁白:将对象建模为“List&lt;Map&lt;String, String&gt;&gt;”而不是自定义类,然后进一步使用“List&lt;CustomClass&gt;”,并没有多大好处。 (2认同)