Loop through an ArrayList of HashMaps Java

36,488

Solution 1

the [] operator can only be used on arrays. List has a get(int index) method to get the element at a given index:

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

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

Solution 2

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
Share:
36,488
AmericanSuave
Author by

AmericanSuave

Updated on July 05, 2022

Comments

  • AmericanSuave
    AmericanSuave almost 2 years
    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.

    I was doing a nested for loop to so 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 this does not work. How do I acess all the keys of my hashmap if their in the arraylist? How can I accomplish this?