How to swap arrayMap values and keys in Java

前端 未结 4 671
孤独总比滥情好
孤独总比滥情好 2021-01-15 06:04

I\'m having a bit of trouble reversing a given map and storing its reversed keys and values into another map. I have a method prototype as follows:

public st         


        
4条回答
  •  借酒劲吻你
    2021-01-15 06:33

    I would first suggest writing a Graph class which abstracts away the underlying Map data structure. Of course, this just pushes the implementation to the Graph interface rather than dealing directly with the Map interface.

    So for now, stick with your map:

    Map> graph;
    Map> reverse;
    

    I suggest using Map.entrySet() to get the set of entries from your graph. Then for each Map.Entry, retrieve the key and value of each one. Next, for each "vertex" in the value Set, insert the key into the Set which is associated with the vertex.

    This might be more clear if I formatted it similar to Java code rather than English sentences. I hope you get the basic idea. Of course, using a pre-made and pre-tested solution would be preferrable if it fits into your constraints of project.

提交回复
热议问题