作者:doliangzhe | 来源:互联网 | 2023-01-11 14:24
让我们假设我们得到了以下两个数组
String[] keys = new String[] {"a", "b", "c", "aa", "d", "b"}
int[] values = new int[] { 1 , 2 , 3 , 4 , 5 , 6 }
通过将这两个数组合并到HashTable中,我们得到以下结果
// pseudo-code
Map 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个数组,按键和值合并它们,其中value是重复键的所有值的总和.我们应该怎么做?
1> Eran..:
你去:
Map 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
阵列.
@nullpointer`Map`不保证迭代顺序,因此输出对于所有意图和目的都是相同的.