在Java中将多个映射添加到列表
我有多张地图(比如100张或更多)。我想把它们列在下面的列表中:在Java中将多个映射添加到列表,java,list,arraylist,Java,List,Arraylist,我有多张地图(比如100张或更多)。我想把它们列在下面的列表中: HashMap<String, Integer> map1 = new HashMap<>(); map1.put("x", 47); ... nextmap here... ArrayList mapsList=new arrylist(Arrays.asList(map1,map2,map3…,map100); 有没有一种方法可以将所有这些放在一个循环中,以避免将同一个名称写一百次,只改变其中的数字
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("x", 47);
...
nextmap here...
ArrayList mapsList=new arrylist(Arrays.asList(map1,map2,map3…,map100);
有没有一种方法可以将所有这些放在一个循环中,以避免将同一个名称写一百次,只改变其中的数字
@编辑
我有一张这样的地图:
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("x", 47);
...
nextmap here...
HashMap map1=newhashmap();
map1.put(“x”,47);
...
下一个地图在这里。。。
使用方法生成地图,插入值并将其添加到列表中
public Map<String, Integer> newMap(Values... values){
Map<String, integer> map = new HashMap<>();
for(Values v : values){
map.put(v.getKey(), v.getValue());
}
list.add(map);
return map;
}
这样,您就不需要使用map1
、map2
、map3
,只需调用该方法即可
newMap(new Values("x", 47), new Values("y", 12));
newMap(new Values("x", 4));
…您将映射放在100个不同的变量中?不,一个接一个。每个映射都在其自己的变量中吗?您的错误是首先创建变量
map1
,map2
,…。list.add(new HashMap());
在一个方法中,如果需要,您需要在其中插入值。@soummy12因为作为单个变量,您不能对它们进行集体引用。只需将它们直接放入一个列表中,而不将它们放入单个变量中,就可以省力了。