列表转映射

huangapple go评论78阅读模式
英文:

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&lt;Map&lt;String, Object&gt;&gt; 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&lt;Object, Object&gt; hm2 = new HashMap&lt;Object, Object&gt;();
list.stream().flatMap(map -&gt; map.entrySet().stream())
        .forEach(entry -&gt; 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&lt;Object, Object&gt; res = list.stream()
        .collect(Collectors.toMap(
                e -&gt; e.get(&quot;date_part&quot;),
                e -&gt; e.get(&quot;count&quot;)));

huangapple
  • 本文由 发表于 2020年10月17日 01:48:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64394042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定