Reverse HashMap keys and values in Java

前端 未结 8 1703
梦谈多话
梦谈多话 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:23

    I wrote a simpler loop that works too (note that all my values are unique):

    HashMap<Character, String> myHashMap = new HashMap<Character, String>();
    HashMap<String, Character> reversedHashMap = new HashMap<String, Character>();
    
    for (char i : myHashMap.keySet()) {
        reversedHashMap.put(myHashMap.get(i), i);
    }
    
    0 讨论(0)
  • 2020-11-27 18:29

    They all are unique, yes

    If you're sure that your values are unique you can iterate over the entries of your old map .

    Map<String, Character> myNewHashMap = new HashMap<>();
    for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
        myNewHashMap.put(entry.getValue(), entry.getKey());
    }
    

    Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse() method :

    BiMap<Character, String> myBiMap = HashBiMap.create();
    myBiMap.put('a', "test one");
    myBiMap.put('b', "test two");
    
    BiMap<String, Character> myBiMapInversed = myBiMap.inverse();
    

    As java-8 is out, you can also do it this way :

    Map<String, Integer> map = new HashMap<>();
    map.put("a",1);
    map.put("b",2);
    
    Map<Integer, String> mapInversed = 
        map.entrySet()
           .stream()
           .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))
    

    Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:

    Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();
    
    0 讨论(0)
提交回复
热议问题