通过流将地图列表转换为单个地图

通过流将地图列表转换为单个地图

问题描述:

我在数据库中查询两列,其中第一列是第二列的关键字. 如何将结果列表转换为单个地图? 可能吗?我刚刚看过豆子的例子.

I query the DB for two columns where the first one is the key to the second one. How can I convert the resulting list to a single map? Is it even possible? I have just seen examples with beans.

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:

You forgot to convert your key and value mappings to produce 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