本文介绍了将地图列表合并到单个地图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Map列表合并为一个列表:

I'm trying to merge a list of Map into a single one:

List<Map<String, List<Long>>> dataSet;
Map<String, Set<Long>> uniqueSets = dataset.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        Collector.of(
            HashSet<Long>::new,
            ...,
            ...
        )
    ));

这个想法是uniqueSet应该在每个集合(由字符串标识)中保存一个唯一ID(Long)的列表.但是我不确定...部分.

The idea is that uniqueSet should hold a list of unique IDs (Longs) within each collection (identified by a String). But I'm not sure about the ... parts.

对于所请求的示例(使用JSON):

As for the requested example (in JSON):

输入:

[
    {
        "Collection1": [1, 2, 3, 3],
        "Collection2": [2, 3]
    },
    {
        "Collection1": [3, 4],
        "Collection3": [1, 2]
    }
]

输出:

{
    "Collection1": [1, 2, 3, 4],
    "Collection2": [2, 3],
    "Collection3": [1, 2]
}

推荐答案

如果我理解了您的问题,并给出了以下两张地图:

If I understood your question, if given these two maps:

{Mike=[5, 6], Jack=[1, 2, 3]}
{Fred=[7, 8], Jack=[4, 5]}

您要像这样组合它们:

{Mike=[5, 6], Fred=[7, 8], Jack=[1, 2, 3, 4, 5]}

您在这里:

Map<String, List<Long>> uniqueSets = dataset.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        Collector.of(
            ArrayList<Long>::new,
            (list, item) -> list.addAll(item.getValue()),
            (left, right) -> { left.addAll(right); return left; })
    ));

也就是说:

  • 您对供应商的理解是正确的:创建一个新的ArrayList来累积价值
  • 第二个部分是累加器:它是一个容器(列表)和一个项目,并将该项目添加到容器中的东西.请注意,这些项目是Map.Entry实例.
  • 最后一块是组合器,用于将两个由累加器填充的容器合并为一个容器
  • You got the supplier right: create a new ArrayList to accumulate values
  • The second piece is the accumulator: something that takes a container (the list) and an item, and adds the item to the container. Note that the items are Map.Entry instances.
  • The final piece is a the combiner, to merge two containers populated by accumulators into one

这篇关于将地图列表合并到单个地图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:52