Java 创建另一个地图的地图
我有一张这样的地图:Java 创建另一个地图的地图,java,Java,我有一张这样的地图: Map<String, List<Integer>> map = new TreeMap<>(); one, [-55, -55, -54, -54, -55, -54, -54, -54, -54, -55] two, [-61, -61, -61, -61, -60, -61, -60, -61, -60, -60] three, [-69, -69, -68, -68, -68, -69, -70, -68, -69, -69]
Map<String, List<Integer>> map = new TreeMap<>();
one, [-55, -55, -54, -54, -55, -54, -54, -54, -54, -55]
two, [-61, -61, -61, -61, -60, -61, -60, -61, -60, -60]
three, [-69, -69, -68, -68, -68, -69, -70, -68, -69, -69]
我创建了一个名为“addRandomValuesToList”的方法,它查看名为input的整数列表,获取4个值并将它们放入另一个名为randomValues的列表中
public static List<Integer> addRandomValuesToList(List<Integer> input)
{
List<Integer> randomValues = new ArrayList<>();
...
return randomValues
}
我很难做到这一点。我试过这样的方法:
Map<String, List<Integer>> test = new TreeMap<>();
for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
newList = addRandomValuesToList(entry.getValue());
test.put(entry.getKey(), newList);
}
Map test=newtreemap();
对于(Map.Entry:Map.entrySet()){
newList=addRandomValuesToList(entry.getValue());
test.put(entry.getKey(),newList);
}
这会导致测试映射中的某些列表完全为空。是我做错了什么,还是我的方法错了?应该尽可能将变量声明为局部变量。(它将在循环中仅存储内存一次。) 此外,Map.Entry由Map的内部数据支持。所以它有一个方法
setValue
,当然不是setKey
Map<String, List<Integer>> test = new TreeMap<>();
for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
List<Integer> newList = addRandomValuesToList(entry.getValue());
entry.setValue(newList);
}
addRandomValuesToList
:如果它确实修改了传递的条目值,则该方法可能无效,无需对结果进行任何处理
关于这个错误我不确定。映射中的每个列表都必须是一个新实例(
new ArrayList()
或诸如此类)。在addRandomValuesToList()
方法中共享代码addRandomValuesToList
?可能重复
Map<String, List<Integer>> test = new TreeMap<>();
for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
List<Integer> newList = addRandomValuesToList(entry.getValue());
entry.setValue(newList);
}
entry.getValue().add(42);