简体   繁体   中英

How to add a list into another list from a HashMap

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
}

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
}

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM