Convert List of Maps to single Map via streams

后端 未结 4 1268
时光取名叫无心
时光取名叫无心 2020-12-06 03:00

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

4条回答
  •  日久生厌
    2020-12-06 03:24

    You forgot to convert your key and value mappings to produce String:

    final Map 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> steps = queryForList("SELECT key, value FROM table");
        final Map 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> queryForList(String s) {
        final List> result = new ArrayList<>();
    
        for (int i = 0; i < 10; i++) {
            final Map 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
    

提交回复
热议问题