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

时间:2015-04-17 03:26:02

标签: java dictionary treemap

我的任务是编写代码来交换地图值(非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。但这只会让事情变得更糟。

我如何实现我的目标,即分别将地图条目分解为新的集合和字符串中的键和值?这可能是使用我的起点,还是根本不可能?

2 个答案:

答案 0 :(得分:1)

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

让我用一个简单的片段解释你:

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

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

答案 1 :(得分:0)

这将为您提供相反的地图。

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