Search code examples
javadictionarytreemap

Java: implementing Treemap methods on map.entry, possible?


My assignment is to write code that swaps the keys for the values of a map (with non 1:1) ratio, and I thought to create a TreeMap. So far I have:

   public static Map<String, Set<String>> reverseMapping(Map<String, String> mapping) {
    TreeMap <String, String> temp = (TreeMap<String, String>) mapping;


    while (temp.pollFirstEntry() !=null ){
         Map.Entry<String, String> iter=temp.pollFirstEntry();
         String newKey = iter.get(iter.firstKey());
    }

but it's saying that first.Key() is undefined for map.entry and suggests I cast iter. but that just makes things worse.

How can I achieve my goal of breaking the map entry down into its keys and values in a new set and string, respectively? Is this possible using the starting point I have, or at all?


Solution

  • As per your comments, what you want to know is how to iterate over each entries of a map.

    Let me explain you how with a simple snippet :

    for(Map.Entry<String, String> entry : temp.entrySet())
    {
        String key = entry.getKey();
        String value = entry.getValue();
    }
    

    I'm pretty sure you can solve your issue now.