Loop through ArrayList from HashMaps Java

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

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

I have several hashmaps in my list of arrays and I want to compare hashmaps for duplicates like 0.1 0.2 0.3 0.4 .... 1.2 1.3 1.4 ..... 2, 3 2.4, etc.

I did a nested loop for this, but got stuck on how to access the hashmaps and tried this

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 that does not work. How can I use all the keys of my hash map if they are in the archivist? How can i do this?

+5
source share
2 answers

The operator []can only be used for arrays. List has a method get(int index)for getting an element at a given index:

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

Java classes are documented: http://docs.oracle.com/javase/6/docs/api/

+7
source

.

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
+7

All Articles