Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

java - Convert List of Maps to single Map via streams

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")));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")));

Full example

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;
}

Which prints

key1 -> value1
key2 -> value2
key0 -> value0
key5 -> value5
key6 -> value6
key3 -> value3
key4 -> value4
key9 -> value9
key7 -> value7
key8 -> value8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...