Convert Multivalued map to HashMap I have a Multivalued map (javax.ws.rs.core.MultivaluedMap&lt;String, String&gt;) which I want to convert to regular HashMap so I got below code:

private Map&lt;String, String&gt; convertMultiToRegularMap(MultivaluedMap&lt;String, String&gt; m) {
    Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
    if (m == null) {
        return map;
    }
    for (Entry&lt;String, List&lt;String&gt;&gt; entry : m.entrySet()) {
        String qKey = entry.getKey();
        List&lt;String&gt; values = entry.getValue();
        if (values.size() &gt; 1) {
            String val = "";
            int i = 0;
            for (String s : values) {
                if (i &gt; 0) {
                    val += ",";
                }
                val += s;
                i++;
            }
            map.put(qKey, val);
        } else {
            map.put(qKey, values.get(0));
        }
    }
    return map;
}


Is there any improvement I can do here? I am using Java7.
The main part of the code is converting the List&lt;String&gt; value into a String delimited by a comma. Instead of using an external i variable, you can use a StringBuilder and append the comma or not depending on whether it is empty or not.

Regarding your current code:


Try to avoid concatenating String with +. You should use a StringBuilder when necessary.
You don't need to make a separate code path for the case where the list is empty in the map value: the regular path handles it also.
You don't need to store the key and the value in local variables.
It is indeed a very good idea to return a new empty map instead of null when the incoming map is null.
If the value stored in the multimap is an empty list, then your code will throw an exception because it tries to access the element 0 when there is no such element.


This would be a proposed code for Java 7:

private Map&lt;String, String&gt; convertMultiToRegularMap(MultivaluedMap&lt;String, String&gt; m) {
    Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
    if (m == null) {
        return map;
    }
    for (Entry&lt;String, List&lt;String&gt;&gt; entry : m.entrySet()) {
        StringBuilder sb = new StringBuilder();
        for (String s : entry.getValue()) {
            if (sb.length() &gt; 0) {
                sb.append(',');
            }
            sb.append(s);
        }
        map.put(entry.getKey(), sb.toString());
    }
    return map;
}




As a side-note, when you'll upgrade to Java 8, this code can be made simpler by using the new String.join(delimiter, elements) method.