如何使用 Java 流将两个数组合并到一个映射中?
How to merge two arrays into a map using Java streams?
假设我们得到了以下两个数组
String[] keys = new String[] {"a", "b", "c", "aa", "d", "b"}
int[] values = new int[] { 1 , 2 , 3 , 4 , 5 , 6 }
通过将这 2 个数组合并到哈希表中,我们得到以下结果
// 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 风格来做到这一点?
到目前为止我有以下内容:
// 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 个数组,按键和值合并它们,其中值是重复键的所有值的总和。我们该怎么做?
好了:
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}
这与您发布的代码段非常相似,但出于某种原因,您发布的代码段未包含对 keys
和 values
数组的引用。
我不喜欢在引用索引时使用流,但您可以使用 groupingBy
and summingInt
来完成此操作:
Map<String, Integer> result = IntStream.range(0, keys.length)
.boxed()
.collect(
Collectors.groupingBy(
i -> keys[i],
Collectors.summingInt(i -> values[i])
)
);
请注意,这基于键和值长度相等的假设,因此您可能需要进行一些额外的验证。
假设我们得到了以下两个数组
String[] keys = new String[] {"a", "b", "c", "aa", "d", "b"}
int[] values = new int[] { 1 , 2 , 3 , 4 , 5 , 6 }
通过将这 2 个数组合并到哈希表中,我们得到以下结果
// 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 风格来做到这一点?
到目前为止我有以下内容:
// 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 个数组,按键和值合并它们,其中值是重复键的所有值的总和。我们该怎么做?
好了:
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}
这与您发布的代码段非常相似,但出于某种原因,您发布的代码段未包含对 keys
和 values
数组的引用。
我不喜欢在引用索引时使用流,但您可以使用 groupingBy
and summingInt
来完成此操作:
Map<String, Integer> result = IntStream.range(0, keys.length)
.boxed()
.collect(
Collectors.groupingBy(
i -> keys[i],
Collectors.summingInt(i -> values[i])
)
);
请注意,这基于键和值长度相等的假设,因此您可能需要进行一些额外的验证。