我正在尝试使用 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对象?
最佳答案
您可以在每个 Map
的 keySet
上使用 flatMap
:
List<String> output = lst.stream()
.flatMap(mp -> mp.keySet().stream())
.collect(Collectors.toList());
关于java - 使用流从 Map 对象列表中仅获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59835334/