简体   繁体   English

如何使用Java流将两个数组合并到一个映射中?

[英]How to merge two arrays into a map using Java streams?

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 }

And by merging these 2 arrays into HashTable we get the following 通过将这两个数组合并到HashTable中,我们得到以下结果

// 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)
);

How can we do this using java Lambda style? 我们怎么能用java Lambda样式做到这一点?

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

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. 但是,我想采用2个数组,按键和值合并它们,其中value是重复键的所有值的总和。 How can we do this? 我们应该怎么做?

There you go: 你去:

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

Output: 输出:

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

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. 这与您发布的代码段非常相似,但由于某些原因,您发布的代码段不包含对keysvalues数组的引用。

I don't like using streams when referring to indexes, but you can use groupingBy and summingInt to accomplish this: 我不喜欢在引用索引时使用流,但是你可以使用groupingBysummingInt来完成这个:

Map<String, Integer> result = IntStream.range(0, keys.length)
   .boxed()
   .collect(
       Collectors.groupingBy(
           i -> keys[i],
           Collectors.summingInt(i -> values[i])
       )
   );

Note that this works on the assumption that keys and values are both of equal length, so you may want to do some additional validation. 请注意,这可以假设键和值都具有相同的长度,因此您可能需要进行一些额外的验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM