简体   繁体   English

循环遍历HashMaps Java的ArrayList

[英]Loop through an ArrayList of HashMaps Java

ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();

    HashMap<String, Integer> check = new HashMap<String, Integer>();

I have some number of hashmaps in my array list and I want to compare the hashmaps for duplicates like this 0,1 0,2 0,3 0,4....1,2 1,3 1,4.....2,3 2,4 etc. 我的数组列表中有一些哈希映射,我想比较重复的哈希图,如0,1 0,2 0,3 0,4 .... 1,2 1,3 1,4 .... .2,3 2,4等

I was doing a nested for loop to so this but got stuck on how to access the hashmaps and tried this 我正在做一个嵌套for循环,所以这个但是卡在如何访问哈希映射并尝试了这个

for (int a =0; a<myList.size();a++){
            for(int b=a+1; b<myList.size();b++){
                for (String key : myList[a].check.keySet())
            }
        }

But this does not work. 但这不起作用。 How do I acess all the keys of my hashmap if their in the arraylist? 如果他们在arraylist中我如何访问我的hashmap的所有键? How can I accomplish this? 我怎么能做到这一点?

Here is an example to iterate. 这是一个迭代的例子。 I created dummy data to test the code 我创建了虚拟数据来测试代码

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
            }

        }       
    }

Output is 输出是

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

the [] operator can only be used on arrays. []运算符只能在数组上使用。 List has a get(int index) method to get the element at a given index: List有一个get(int index)方法来获取给定索引处的元素:

for (String key : myList.get(a).keySet()) {
    ...
}

Java classes are documented: http://docs.oracle.com/javase/6/docs/api/ Java类已记录在案: http//docs.oracle.com/javase/6/docs/api/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM