Java:在 map.entry 上实现 Treemap 方法,可能吗?

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

我的任务是编写代码,将键与映射值(非 1:1)比率交换,我想创建一个 TreeMap。到目前为止我有:

   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());
    }

但是它说 first.Key() 对于 map.entry 是未定义的,并建议我投射 iter。但这只会让事情变得更糟。

如何实现将映射条目分解为新集合和字符串中的键和值的目标?这是否可能使用我的起点,或者根本没有?

根据您的评论,您想知道的是如何迭代地图的每个条目。

让我用一个简单的片段向您解释一下:

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

我很确定你现在可以解决你的问题。

这会给你地图的反面。

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");

        TreeMap<String, String> tm1 =new TreeMap<String, String>();

        tm1.put("Hello" , "Me");
        tm1.put("Bye", "Jim");


        TreeMap<String , String > reverse = reverse(tm1);
        System.out.println(reverse);


     }

     public static TreeMap<String , String > reverse(TreeMap<String, String> tm1){

                   TreeMap<String , String > reverse =new TreeMap<String, String>();
         for(String s : tm1.keySet())
         {

             String v= tm1.get(s);

             reverse.put(v,s);


         }

         return reverse;
     }
}