I am trying to store hashmap keys and values to a list, then nest the list in another list. So something like:
Hashmap contains - [ {3,1} , {2, 1}, {1,1} ]
I want to add {3,1}, {2, 1}, {1,1} into 3 different List respectively.
Next, I will add the 3 lists to an outer list, nesting the 3 lists in an inner list.
But I would like to understand why my code below doesnt work? My nestedList below will get referenced to tempList which i dont understand.
List<Integer> tempList = new ArrayList<>();
List<List<Integer>> nestedList = new ArrayList<>();
Map<Integer,Integer> map = new HashMap<>();
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
tempList.clear(); //once it run this, nestedList will be cleared too. Why?
tempList.add(entry.getKey());
tempList.add(entry.getValue());
nestedList.add(tempList); //tempList will get referenced to nestedList
}
CodePudding user response:
Object type is passed by reference in Java, you need to change your code as follows:
List<List<Integer>> nestedList = new ArrayList<>();
Map<Integer,Integer> map = new HashMap<>();
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
List<Integer> tempList = new ArrayList<>();
tempList.add(entry.getKey());
tempList.add(entry.getValue());
nestedList.add(tempList); //tempList will get referenced to nestedList
}
CodePudding user response:
There is a single instance for tempList, and keep adding & clear while looping the map. I guess it needs to create a new tempList in map loop:
List<List<Integer>> nestedList = new ArrayList<>();
Map<Integer,Integer> map = new HashMap<>();
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
List<Integer> tempList = new ArrayList<>();
tempList.add(entry.getKey());
tempList.add(entry.getValue());
nestedList.add(tempList);
}
CodePudding user response:
Try this.
Map<Integer, Integer> map = Map.of(3, 1, 2, 1, 1, 1);
List<List<Integer>> nestedList = map.entrySet().stream()
.map(e -> List.of(e.getKey(), e.getValue()))
.toList();
System.out.println(nestedList);
output:
[[1, 1], [2, 1], [3, 1]]