0

How can i print all the values from the following hashmap

ServletContext appScope = request.getServletContext();
        Map<String, List<String>> onLine = (HashMap<String, List<String>>)appScope.getAttribute("User");
        if(onLine != null) {
            out.print(onLine.get("1"));
        }
davioooh
  • 23,742
  • 39
  • 159
  • 250
rhsabbir
  • 247
  • 1
  • 6
  • 19

5 Answers5

2
if (onLine != null) {
    for (String k : onLine.keySet()) {
        for (String v : onLine.get(k)) {
            out.print(v);
        }
    }
}
Marco Bolis
  • 1,222
  • 2
  • 15
  • 31
2

java.util.Map has a values() method just for this:

for(List<String> nextArray : onLine.values()) {
    for(String nextString : nextArray) {
        out.print(nextString);
    }
}
Peter Bratton
  • 6,302
  • 6
  • 39
  • 61
1

Try this:

if (onLine != null) {
    for (String key : onLine.keySet()) {
        for (List<String> val : onLine.get(key)) {
            for(String str : val){
                System.out.print(str);
            }
        }
    }
}

This will print all the strings in your map.

davioooh
  • 23,742
  • 39
  • 159
  • 250
1

if you need both key and values:

for( Map.Entry<String, List<String>> e : yourMap.entrySet() )
  System.out.println( "key=" + e.key() + ", value=" + e.value() );
injecteer
  • 20,038
  • 4
  • 45
  • 89
1

I wrote a demo, you can try it

public static void main(String[] args) {

         Map<String, Integer> map = new HashMap<String, Integer>();
         map.put("k1", 1);
         map.put("k2", 2);
         map.put("k3", 3);
         map.put("k4", 4);
         map.put("k5", 5);

         Set<String> keys = map.keySet();
         for(String key:keys) {
            System.out.println("key:" + key);
            System.out.println("value:" + map.get(key));
         }
}
Ben
  • 54,723
  • 49
  • 178
  • 224