Search code examples
javacollectionsapache-commons

How to split the values from multihashmap?


How to split the values ?

public static void main(String[] args) { 
    // Map<String,Set<String>> dep = new HashMap<String,Set<String>>();
    MultiHashMap mp = new MultiHashMap();

    mp.put("a", "10");
    mp.put("a", "12"); 
    mp.put("a", "11"); 
    mp.put("b", "1"); 
    mp.put("c", "14"); 
    mp.put("e", "");
    mp.put("b", "1");
    mp.put("b", "2");
    mp.put("b", "3");
    List list = null; 

    Set set = mp.entrySet();              
    Iterator i = set.iterator(); 

    while (i.hasNext()) { 
        Map.Entry me = (Map.Entry) i.next(); 
        list = (List) mp.get(me.getKey());

        int itemCount = list.size();
        for (int z = 0; z < itemCount; z++) {
            System.out.println(me.getKey());
            System.out.println(me.getValue());

        }
    }                  
}

But i'm getting values as

e
[]
b
[1, 1, 2, 3]
b
[1, 1, 2, 3]
b
[1, 1, 2, 3]
b
[1, 1, 2, 3]
c
[14]
a
[10, 12, 11]
a
[10, 12, 11]
a
[10, 12, 11]

but i need to display the values as

a:10
a:12
a:11
b:1
b:1
b:2
b:3
c:14
e:

How to print values as like above ?


Solution

  • Try this

    public static void main(String[] args) {
        // Map<String,Set<String>> dep = new HashMap<String,Set<String>>();
        MultiHashMap mp = new MultiHashMap();
        mp.put("a", "10");
        mp.put("a", "12");
        mp.put("a", "11");
        mp.put("b", "1");
        mp.put("c", "14");
        mp.put("e", "");
        mp.put("b", "1");
        mp.put("b", "2");
        mp.put("b", "3");
        List list = null;
    
        Set set = mp.entrySet();
        Iterator i = set.iterator();
        while (i.hasNext()) {
    
            Map.Entry<String, List<String>> me = (Map.Entry) i.next();
    
            for(int j = 0 ; j< me.getValue().size(); j++ )
            {
                System.out.println(me.getKey() +" : " +me.getValue().get(j));
            }
        }
    }
    

    Output is

    e : 
    b : 1
    b : 1
    b : 2
    b : 3
    c : 14
    a : 10
    a : 12
    a : 11