簡體   English   中英

按列表分組的Java流 <Map<String, Object> &gt;到地圖 <Integer, List<Integer> &gt;

[英]Java Stream Grouping by List<Map<String, Object>> to Map<Integer, List<Integer>>

我有一個

List<Map<String, Object>>

來自Spring NamedParameterJdbcTemplate queryForList調用。 數據返回如下所示:

[{"id":5,"uid":6}, {"id":5,"uid":7}, {"id":6,"uid":8}, {"id":7,"uid":7}, {"id":8,"uid":7}, {"id":8,"uid":9}]

如何按以下格式重新排列數據?

{5:[6, 7], 6:[8], 7:[7], 8:[7, 9]}

我希望返回Map<Integer, List<Integer>>

任何人都知道如何實現這一目標? 任何幫助非常感謝?

這是Collectors.groupingBy一個工作,它有一個下游收集器,如Collectors.mapping

 Map<Integer, List<Integer>> result = l.stream()
            .collect(Collectors.groupingBy(
                    m -> (Integer) (m.get("id")),
                    Collectors.mapping(m -> (Integer) m.get("uuid"), Collectors.toList())));

或根本沒有溪流:

list.forEach(x -> {
        Integer key = (Integer) x.get("id");
        Integer value = (Integer) x.get("uuid");
        result.computeIfAbsent(key, ignoreMe -> new ArrayList<>()).add(value);
    });

您可以在使用分組收集器時將鍵和值映射到整數:

List<Map<String, Object>> maps = null;

Map<Integer, List<Integer>> result = maps.stream()
        .collect(Collectors.groupingBy(
                map -> ((Number) map.get("id")).intValue(),
                    Collectors.mapping(map -> ((Number) map.get("uid")).intValue(), 
                            Collectors.toList())));

使用((Number) map.get("id")).intValue()以防萬一值為Long。

我不是流API語法的忠實粉絲:我認為使用普通的舊循環(使用其他一些Java 8-isms)可能更容易:

Map<Integer, List<Integer>> result = new HashMap<>();
for (Map<String, Object> entry : list) {
  int id = (Integer) entry.get("id");
  int uid = (Integer) entry.get("uid");
  result.computeIfAbsent(id, k -> new ArrayList<>())
      .add(uid);
}

當然是YMMV; 我只是認為這比收集器和下游收集器的所有問題更令人愉快,並且當你犯類型錯誤時會出現非明顯的錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM