gpt4 book ai didi

java - 通过流将 map 列表转换为单个 map

转载 作者:行者123 更新时间:2023-12-04 22:56:45 25 4
gpt4 key购买 nike

我在数据库中查询两列,其中第一列是第二列的键。
如何将结果列表转换为单个 map ?
甚至有可能吗?我刚刚看到了 bean 类的例子。

List<Map<String, Object>> steps = jdbcTemplate.queryForList(
"SELECT key, value FROM table");

// well this doesn't work
Map<String, String> result = steps.stream()
.collect(Collectors.toMap(s -> s.get("key"), s -> s.get("value")));

最佳答案

您忘记将键和值映射转换为生成 String :

final Map<String, String> result = steps
.stream()
.collect(Collectors.toMap(s -> (String) s.get("key"),
s -> (String) s.get("value")));
完整示例
public static void main(String[] args) {
final List<Map<String, Object>> steps = queryForList("SELECT key, value FROM table");
final Map<String, String> result = steps
.stream()
.collect(Collectors.toMap(s -> (String) s.get("key"), s -> (String) s.get("value")));
result.entrySet().forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));
}

private static List<Map<String, Object>> queryForList(String s) {
final List<Map<String, Object>> result = new ArrayList<>();

for (int i = 0; i < 10; i++) {
final Map<String, Object> map = new HashMap<>();
map.put("key", "key" + i);
map.put("value", "value" + i);
result.add(map);
}

return result;
}
哪个打印
key1 -> value1
key2 -> value2
key0 -> value0
key5 -> value5
key6 -> value6
key3 -> value3
key4 -> value4
key9 -> value9
key7 -> value7
key8 -> value8

关于java - 通过流将 map 列表转换为单个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com