Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2D arraylist to hashmap in Java

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!

like image 285
BigD Avatar asked Jul 11 '26 08:07

BigD


1 Answers

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:

  1. You should only be using the interface types List, Map ... as types (you only specify the specific impl type such as HashMap when creating new objects!)
  2. Your problem is: when using for-each on List of Lists (as you did) ... you don't get the individual "cells" Instead, you get Lists [ iterating lists of lists ... results in one list per iteration!]

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)

like image 117
GhostCat Avatar answered Jul 13 '26 20:07

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!