[英]How to fetch list from HashMap <String,List<String>> to another list
[英]How to add a list into another list from a HashMap
我正在尝试将 hashmap 个键和值存储到一个列表中,然后将该列表嵌套在另一个列表中。 所以像:
Hashmap 包含 - [ {3,1}, {2, 1}, {1,1} ]
我想将 {3,1}、{2、1}、{1,1} 分别添加到 3 个不同的列表中。
接下来,我会将 3 个列表添加到外部列表,将 3 个列表嵌套在内部列表中。
但我想了解为什么我下面的代码不起作用? 我下面的 nestedList 将引用我不理解的 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
}
Object类型在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
}
尝试这个。
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.