I have Map with values as follows:
Map <Char, ArrayList> numbers;
A: {0,1,2,3}
B:{4,5,6,7}
Now, I can access ArrayLists using numbers.get('A')
but how do I access the elements of arraylist?
Also, I want to get store the elements at each index individually in ArrayList.
For example: ArrayList1: 0,4 and ArrayList2:1,5 and so on.
>Solution :
Arraylists are indexed, meaning that you can access elements by index with the get() method. nums.get(0) //returns first element in nums.
To group the elements at the same index together for numbers
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class Sol {
public static void main(String[] args) {
HashMap<String,ArrayList<Integer>> numbers = new HashMap<>();
numbers.put("A",new ArrayList<>(List.of(0,1,2,3)));
numbers.put("B",new ArrayList<>(List.of(4,5,6,7)));
List<ArrayList<Integer>> values = numbers.values().stream().toList();
HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
for(int j = 0; j < values.get(0).size(); j++) {
ArrayList<Integer> currCol = new ArrayList<Integer>();
for(int i = 0;i < values.size(); i++) {
currCol.add(values.get(i).get(j));
}
map.put("ArrayList"+Integer.valueOf(j).toString(),currCol);
}
System.out.println("");
}
}
I assumed that the number of items in each list is the same.