9

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");
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Prostak
  • 3,565
  • 7
  • 35
  • 46

3 Answers3

15

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);
    }
}
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • Can you add my exact messages into your loop? – Prostak May 05 '11 at 18:03
  • @Prostak check out my edit. sounds like that's what you want. – Bala R May 05 '11 at 18:06
  • 3
    a little late, but does this return in insertion order or do we have to use an iterator? the javadocs for `LinkedHashMap` are identical to that of a `HashMap` – edthethird Apr 11 '13 at 02:02
  • `LinkedHashMap` guarantees it but not all `HashMaps` do: https://stackoverflow.com/questions/2923856/is-the-order-guaranteed-for-the-return-of-keys-and-values-from-a-linkedhashmap-o/2924143 – vsocrates Mar 06 '19 at 21:23
7

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);
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
5

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);
});
Kita
  • 1,548
  • 14
  • 21
Roberto Gimenez
  • 278
  • 4
  • 11