2

我有一个

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>>

任何人都知道我该如何实现这一目标?任何帮助非常感谢?

4

3 回答 3

6

这是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);
    });
于 2018-08-22T21:18:32.190 回答
3

您可以在使用分组收集器时将键和值映射到整数:

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。

于 2018-08-22T21:14:39.127 回答
0

I am not a huge fan of the syntax of the streams API: I think it might be easier to do using a plain old loop (with a few other 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, of course; I just think this is more pleasant than all of the faffing around with collectors and downstream collectors, and the non-obvious error messages when you make type errors.

于 2018-08-22T21:37:26.910 回答