如何在java中打印HashMap中键的所有值

aji*_*mar -6 java hashmap

Map<String, String> map = new HashMap<String, String>();
map.put("1", "xyz");
map.put("1", "abc");
map.put("1", "cde");
map.put("2", "err");`
Run Code Online (Sandbox Code Playgroud)

`

对于上面的地图,我想获得与密钥相关的所有值1.预期输出.

Key :: 1值是:: xyz,abc,cde

值的顺序并不重要.

Jay*_*han 7

在Map中,键应该始终是unique.如果将新值与现有键关联,则它将覆盖现有条目的值.

您可能需要检查Map#put(K,V)方法的界面.

如果映射先前包含键的映射,则旧值将替换为指定的值.

因此,在您的情况下,您的地图将始终"cde"作为密钥的值"1".


new*_*ser 6

使用MultiMap

    MultiMap mapValue = new MultiValueMap();

    mapValue.put("1", "xyz");
    mapValue.put("1", "abc");
    mapValue.put("1", "cde");
    mapValue.put("2", "err");
    System.out.println("Map : " + mapValue);
Run Code Online (Sandbox Code Playgroud)

输出: Map : {2=[err], 1=[xyz, abc, cde]}