【发布时间】:2021-04-21 18:31:47
【问题描述】:
我想知道我是如何实现这种情况的——我有一个整数对 (a,b) 的列表——例如
[[0, 3],[0,3],[0,4],[1,2],[1,8],[1,14],[2,4],[2,5 ],[2,6]] - PairInt 类型列表
The pairInt functionality is defined like this:
class PairInt {
int first, second;
public PairInt(int first, int second) {
this.first = first;
this.second = second;
}
}
我想将此 Integer 对添加到 Map 中,这样它的组织方式如下: {0: [3, 3, 4], 1: [2, 8, 14], 2: [4, 5, 6]}),例如键 0 应该有与之关联的值,依此类推。
假设我有一个这样声明的 HashMap:
HashMap<Integer, List<Integer>> dm = new HashMap<Integer, List<Integer>>();
这可以在 Python 中像这样简单地完成,
mapd= defaultdict(list)
for first, second in pairList:
mapd[first].append(second)
print(mapd)
这是遍历列表并将其添加到地图中,这样就可以采用上述组织。如何在 Java 中为上面提到的 HashMap 结构重现这种行为
建议? 谢谢
【问题讨论】:
标签: java dictionary arraylist hashmap