java 8 - Convert List of Maps to single Map via streams -


i query db 2 columns first 1 key second one. how can convert resulting list single map? possible? have seen examples beans.

list<map<string, object>> steps = jdbctemplate.queryforlist("select key, value table");  // doesn't work map<string, string> result = steps.stream().collect(collectors.tomap(s -> s.get("key"), s -> s.get("value"))); 

you forgot convert key , value mappings 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 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<>();      (int = 0; < 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 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -