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");

3 Answers 3

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);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you add my exact messages into your loop?
@Prostak check out my edit. sounds like that's what you want.
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
LinkedHashMap guarantees it but not all HashMaps do: stackoverflow.com/questions/2923856/…
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);
}

2 Comments

Will this return in the insertion order?
Yes it will ensure insertion order since LinkedHashMap is being used here.
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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.