sanchit bhutani sanchit bhutani - 2 months ago 5
Java Question

I want to traverse the keys and the list in the hash map with the corresponding key i want the value(list) to be printed

I want to traverse the keys and the list in the hash map
with the corresponding key.

Want the value(list) to be printed. Can anyone help?

public class Demo {

public static void main(String[] args) {
HashMap<String,List<String> > hashmapobj = new HashMap<String,List<String>();
List<String> listobj=new ArrayList<String>();
listobj.add("yellow");
listobj.add("green");
listobj.add("orange");
listobj.add("blue");

hashmapobj.put("color", listobj);
hashmapobj.put("light", listobj);

}

}

Answer
for(Map.Entry<String, List<String>> items: hashmapobj.entrySet()){
    System.out.print(items.getKey());
    List<String> list = items.getValue();
    for(String s : list){
        System.out.print(" " + s);
    }
    System.out.println();
}

This will print your key and then all of the values stored in your List<String> on the same line. Each key:value gets its own line.