如何使用Java流将两个数组合并到映射中? [英] How to merge two arrays into a map using Java streams?

查看:177
本文介绍了如何使用Java流将两个数组合并到映射中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们得到了以下两个数组

Lets suppose we were given the following two arrays

String[] keys   = new String[] {"a", "b", "c", "aa", "d", "b"}
int[]    values = new int[]    { 1 ,  2 ,  3 ,  4  ,  5 ,  6 }

通过将这两个数组合并到HashTable中,我们得到以下内容

And by merging these 2 arrays into HashTable we get the following

// pseudo-code
Map<String, Integer> dictionary = new HashTable<>(
  ("a"  => 1)
  ("b"  => 8) // because "b" appeared in index 1 and 5
  ("c"  => 3)
  ("aa" => 4)
  ("d"  => 5)
);

如何使用Java Lambda样式执行此操作?

How can we do this using java Lambda style?

到目前为止,我有以下内容:

So far I have the following:

// this loops through the range given (used for index start and end)
// and sums the values of duplicated keys
tree.listMap = IntStream.range(range[0], range[1]).boxed().collect(
  Collectors.toMap(i - > dictionary[i], i - > i + 1, Integer::sum, TreeMap::new)
);

但是,我想采用2个数组,按键和值合并它们,其中value是重复键的所有值的总和.我们该怎么做?

However, I'd like to take 2 arrays, merge them by key and value, where value is the sum of all values for duplicated keys. How can we do this?

推荐答案

去那里:

Map<String,Integer> themap = 
       IntStream.range (0, keys.length).boxed()
                .collect (Collectors.toMap(i->keys[i],
                                           i->values[i],
                                           Integer::sum,
                                           TreeMap::new));

输出:

{a=1, aa=4, b=8, c=3, d=5}

这与您发布的代码段非常相似,但是由于某些原因,您发布的代码段不包含对keysvalues数组的引用.

This is quite similar to the snippet you posted, though, for some reason, the snippet you posted contains no reference to the keys and values arrays.

这篇关于如何使用Java流将两个数组合并到映射中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆