Reverse HashMap keys and values in Java

前端 未结 8 1789
梦谈多话
梦谈多话 2020-11-27 17:59

It\'s a simple question, I have a simple HashMap of which i want to reverse the keys and values.

HashMap myHashMap = new HashMap<         


        
8条回答
  •  渐次进展
    2020-11-27 18:08

    Tested with below sample snippet, tried with MapUtils, and Java8 Stream feature. It worked with both cases.

    public static void main(String[] args) {
        Map test = new HashMap();
        test.put("a", "1");
        test.put("d", "1");
        test.put("b", "2");
        test.put("c", "3");
        test.put("d", "4");
        test.put("d", "41");
    
        System.out.println(test);
    
        Map test1 = MapUtils.invertMap(test);
    
        System.out.println(test1);
    
        Map mapInversed = 
                test.entrySet()
                   .stream()
                   .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
    
        System.out.println(mapInversed);
    }
    
    Output:
    {a=1, b=2, c=3, d=41}
    {1=a, 2=b, 3=c, 41=d}
    {1=a, 2=b, 3=c, 41=d}
    

提交回复
热议问题