循环遍历HashMaps Java的ArrayList ArrayList myList=new ArrayList(); HashMap check=新建HashMap();
我的数组列表中有一些散列图,我想比较散列图的重复项,如0,10,20,30,4…1,21,31,4…2,32,4等 我做了一个嵌套的for循环来实现这一点,但是遇到了如何访问hashmaps的问题并尝试了这个方法循环遍历HashMaps Java的ArrayList ArrayList myList=new ArrayList(); HashMap check=新建HashMap();,java,arraylist,hashmap,Java,Arraylist,Hashmap,我的数组列表中有一些散列图,我想比较散列图的重复项,如0,10,20,30,4…1,21,31,4…2,32,4等 我做了一个嵌套的for循环来实现这一点,但是遇到了如何访问hashmaps的问题并尝试了这个方法 ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>(); HashMap<String, Integer
ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();
HashMap<String, Integer> check = new HashMap<String, Integer>();
for(int a=0;a只能在数组上使用[]
运算符。List有一个get(int index)
方法来获取给定索引处的元素:
for (int a =0; a<myList.size();a++){
for(int b=a+1; b<myList.size();b++){
for (String key : myList[a].check.keySet())
}
}
Java类是有文档记录的:这里是一个迭代的示例。我创建了虚拟数据来测试代码
for (String key : myList.get(a).keySet()) {
...
}
@巴拉尔:ArrayList
不能用方括号处理。另外,您可能需要更改声明myList的方式:List myList=new ArrayList();@vtheron如果它只是List
,那么应该使用Iterator
而不是直接索引;如果List
恰好是LinkedList
,索引速度会很慢。
private void ArrayListAndHashMap()
{
ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();
HashMap<String, Integer> data1 = new HashMap<String, Integer>();
data1.put("0",new Integer(1));
data1.put("1",new Integer(2));
data1.put("2",new Integer(3));
data1.put("3",new Integer(4));
HashMap<String, Integer> data2 = new HashMap<String, Integer>();
data1.put("10",new Integer(10));
data1.put("11",new Integer(20));
data1.put("12",new Integer(30));
data1.put("13",new Integer(40));
myList.add(data1);
myList.add(data2);
for (int a =0; a<myList.size();a++)
{
HashMap<String, Integer> tmpData = (HashMap<String, Integer>) myList.get(a);
Set<String> key = tmpData.keySet();
Iterator it = key.iterator();
while (it.hasNext()) {
String hmKey = (String)it.next();
Integer hmData = (Integer) tmpData.get(hmKey);
System.out.println("Key: "+hmKey +" & Data: "+hmData);
it.remove(); // avoids a ConcurrentModificationException
}
}
}
Key: 3 & Data: 4
Key: 2 & Data: 3
Key: 10 & Data: 10
Key: 1 & Data: 2
Key: 0 & Data: 1
Key: 13 & Data: 40
Key: 11 & Data: 20
Key: 12 & Data: 30