I have a small question about converting 2d arraylist to hashmap in java. I have a dataset looks like this after reading as 2d arraylist:
0 1
0 2
1 2
1 3
Which first column stands for id and second column stands for the item. I would like to create frequent itemset using hashmap in java, the output should look like
1 0
2 0 1
3 1
I use these codes but I have some trouble on them:
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(Integer elem : data){
map.put(elem[1], elem[0]);
}
Where data is my 2d arraylist.
The error message said that
incompatible types: ArrayList<Integer> cannot be converted to Integer
for(Integer elem : data){
^
Any help will be appreciated!
You go like this:
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);
}
Some notes:
So, what is left then is to fetch the elements of that inner List, and push them into the Map. The one other part to pay attention to: you want to create a Map of List objects. And those List objects need to be created as well!
( I didn't run the above through a compiler, so beware of typos, but in general it should be telling you what you need to know. If you don't get what the code is doing, I suggest adding println statements or running it in a debugger)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With