Search code examples
javajava-8java-stream

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

Solution

  • 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