英文:
List to Map Conversion
问题
List<Map<String, Object>> list = jtemplate.queryForList(sql, rmid);
上述语句返回以下列表:
[{date_part=3, count=1}, {date_part=11, count=1}, {date_part=10, count=2}]
现在,我想要的输出是:
{3=1, 11=1, 10=2}
我只想提取date_part
的值,并将其作为映射中的键,count
作为映射的值。
我尝试过这样做,但是我无法获得期望的结果。
Map<Object, Object> hm2 = new HashMap<Object, Object>();
list.stream()
.forEach(map -> hm2.put(map.get("date_part"), map.get("count")));
System.out.println(hm2);
上述代码的输出结果是:
{3=1, 11=1, 10=2}
英文:
List<Map<String, Object>> list = jtemplate.queryForList(sql, rmid);
The above statement returns the following List:
[{date_part=3, count=1}, {date_part=11, count=1}, {date_part=10, count=2}]
Now, I want the output to be
{3=1, 11=1, 10=2}
I just want to extract the date_part's value and store it as the key in the map and count as the value of the map.
I tried doing this but I am unable to get the desired result.
Map<Object, Object> hm2 = new HashMap<Object, Object>();
list.stream().flatMap(map -> map.entrySet().stream())
.forEach(entry -> hm2.put(entry.getKey(), entry.getValue()));
System.out.println(hm2);
The output for the above code is :
{count=1, date_part=11}
答案1
得分: 0
你可以使用 Collectors.toMap
来收集为 Map:
Map<Object, Object> res = list.stream()
.collect(Collectors.toMap(
e -> e.get("date_part"),
e -> e.get("count")));
英文:
You can use Collectors.toMap
to collect as Map:
Map<Object, Object> res = list.stream()
.collect(Collectors.toMap(
e -> e.get("date_part"),
e -> e.get("count")));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论