How to swap keys and values in a Map elegantly

前端 未结 8 1876
滥情空心
滥情空心 2020-12-25 14:49

I already know how to do it the hard way and got it working - iterating over entries and swapping \"manually\". But i wonder if, like so many tasks, this one can be solved

8条回答
  •  天命终不由人
    2020-12-25 15:01

    This will work for duplicate values in the map also, but not for HashMap as values.

    package Sample;
    
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    
    public class Sample {
        public static void main(String[] args) { 
            Map map = new HashMap(); 
            Map > newmap = new HashMap >(); 
    
            map.put("1", "a"); 
            map.put("2", "a"); 
            map.put("3", "b"); 
            map.put("4", "b"); 
            System.out.println("before Reversing \n"+map.toString()); 
    
            for (Map.Entry entry : map.entrySet()) 
            { 
                String oldVal = entry.getValue(); 
                String oldKey = entry.getKey(); 
                Set newVal = null; 
    
                if (newmap.containsKey(oldVal)) 
                { 
                    newVal = newmap.get(oldVal); 
                    newVal.add(oldKey); 
                } 
                else 
                { 
                    newVal= new HashSet<>(); 
                    newVal.add(oldKey); 
                } 
                newmap.put(oldVal, newVal); 
            } 
            System.out.println("After Reversing \n "+newmap.toString()); 
        } 
    }
    

提交回复
热议问题