Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a loop through LinkedHashMap<String,ArrayList<String>>?

Please help me to create a loop through LinkedHashMap<String,ArrayList<String>> h:

if (h.get("key1").size() == 0)
    System.out.println("There is no errors in key1.");
else
    System.out.println("ERROR: there are unexpected errors in key1.");

if (h.get("key2").size() == 0)
    System.out.println("There is no errors in key2.");
else
    System.out.println("ERROR: there are unexpected errors in key2.");

if (h.get("key3").size() == 0)
    System.out.println("There is no errors in key3.");
else
    System.out.println("ERROR: there are unexpected errors in key3.");

if (h.get("key4").size() == 0)
    System.out.println("There is no errors in key4.\n");
else
    System.out.println("ERROR: there are unexpected errors in key4.\n");
like image 628
Prostak Avatar asked May 05 '11 17:05

Prostak


3 Answers

Like this?

for (String key : h.keySet())
{
    System.out.println("Key: " + key);   
    for(String str : h.get(key))
    {
       System.out.println("\t" +str);
    }
}

EDIT:

for (String key : h.keySet())
{
    if(h.get(key).size() == 0)
    {
         System.out.println("There is no errors in " + key) ;
    }
    else
    {
        System.out.println("ERROR: there are unexpected errors in " + key);
    }
}
like image 187
Bala R Avatar answered Nov 11 '22 15:11

Bala R


Try this code:

Map<String, ArrayList<String>> a = new LinkedHashMap<String, ArrayList<String>>();
Iterator<Entry<String,ArrayList<String>>> itr = a.entrySet().iterator();
while (itr.hasNext()) {
    Entry<String,ArrayList<String>> entry = itr.next();
    String key = entry.getKey();
    System.out.println("key: " + key);
    List<String> list = entry.getValue();
    System.out.println("value: " + list);
}
like image 27
anubhava Avatar answered Nov 11 '22 13:11

anubhava


Another way in Java8 is with the foreach() method

Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
    System.out.println(key + " -> " + value);
});
like image 5
Roberto Gimenez Avatar answered Nov 11 '22 13:11

Roberto Gimenez