[英]Convert 2D arraylist to hashmap in Java
我有一个关于在Java中将2d arraylist转换为hashmap的小问题。 在阅读为2d arraylist之后,我有一个数据集看起来像这样:
0 1
0 2
1 2
1 3
哪个第一列代表id,第二列代表该项目。 我想在java中使用hashmap创建频繁的itemset,输出应该是这样的
1 0
2 0 1
3 1
我使用这些代码,但我遇到了一些麻烦:
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(Integer elem : data){
map.put(elem[1], elem[0]);
}
数据是我的2d arraylist。
错误消息说
incompatible types: ArrayList<Integer> cannot be converted to Integer
for(Integer elem : data){
^
任何帮助将不胜感激!
你这样:
List<List<Integer>> inputData = ...
Map<Integer, List<Integer>> dataAsMap = new HashMap<>();
for(List<Integer> row : data){
Integer id = row.get(0);
Integer item = row.get(1);
List<Integer> rowInMap = dataAsMap.get(item);
if (rowInMap == null) {
rowInMap = new ArrayList<>();
dataAsMap.put(item, rowInMap);
}
rowInMap.add(id);
}
一些说明:
那么,剩下的就是获取内部List的元素,并将它们推送到Map中。 另外要注意的部分是:要创建List对象的Map。 还需要创建那些List对象!
(我没有通过编译器运行上面的内容,所以要小心打字错误,但一般来说它应该告诉你需要知道什么。如果你没有得到代码正在做什么,我建议添加println语句或运行它在调试器中)
这是一种简单的方法:
Map<Integer, List<Integer>>
程序:
class FooBar {
public static void main (String[] args) throws Exception {
int[][] data = {{0,1}, {0,2}, {1,2}, {1,3}};
Map<Integer, List<Integer>> myMap = new HashMap<>();
for(int i = 0; i < 4; i++) {
List<Integer> values = myMap.containsKey(data[i][0]) ?
myMap.get(data[i][0]) : new ArrayList<>();
values.add(data[i][1]);
myMap.put(data[i][0], values);
}
System.out.println(myMap);
}
}
输出:
{0=[1, 2], 1=[2, 3]}
这只是为了说明基本方法。 您可以明显地修改它以满足您的需求。 例如,您可以使用String
而不是List<Integer>
并选择将值附加到String
而不是将其添加到List
。
编辑:
这是一个以List<List<Integer>>
作为输入的示例程序。 这里我假设这个列表的名称作为input
。
程序:
class FooBar {
public static void main (String[] args) throws Exception {
/* Input Data */
List<List<Integer>> input = new ArrayList<>();
input.add(new ArrayList<Integer>(){{add(0); add(1);}});
input.add(new ArrayList<Integer>(){{add(0); add(2);}});
input.add(new ArrayList<Integer>(){{add(1); add(2);}});
input.add(new ArrayList<Integer>(){{add(1); add(3);}});
Map<Integer, List<Integer>> myMap = new HashMap<>();
for(int i = 0; i < input.size(); i++) {
List<Integer> values = myMap.containsKey(input.get(i).get(0)) ?
myMap.get(input.get(i).get(0)) : new ArrayList<>();
values.add(input.get(i).get(1));
myMap.put(input.get(i).get(0), values);
}
System.out.println(myMap);
}
}
输出:
{0=[1, 2], 1=[2, 3]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.