【问题标题】:How to add a list into another list from a HashMap如何将列表从 HashMap 添加到另一个列表中
【发布时间】:2021-11-21 20:19:25
【问题描述】:

我正在尝试将 hashmap 键和值存储到一个列表中,然后将该列表嵌套在另一个列表中。所以像:

Hashmap 包含 - [ {3,1} , {2, 1}, {1,1} ]

我想分别将 {3,1}、{2, 1}、{1,1} 添加到 3 个不同的 List 中。

接下来,我会将这 3 个列表添加到一个外部列表中,将这 3 个列表嵌套在一个内部列表中。

但我想了解为什么下面的代码不起作用?我下面的嵌套列表将被引用到我不理解的 tempList。

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
}

【问题讨论】:

    标签: java list hashmap nested-lists


    【解决方案1】:

    对象类型在Java中是通过引用传递的,你需要修改你的代码如下:

    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
    }
    

    【讨论】:

      【解决方案2】:

      试试这个。

      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);
      

      输出:

      [[1, 1], [2, 1], [3, 1]]
      

      【讨论】:

        猜你喜欢
        • 2020-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-22
        • 1970-01-01
        • 2021-01-11
        • 1970-01-01
        相关资源
        最近更新 更多