在java中索引Treemap值

时间:2014-01-05 04:37:53

标签: java indexing treemap

我有成对的Treemap,需要找到一个特定的值,找到它的位置(索引)并做一些计算。 for循环确实找到了特定值,但它基于System.out.println输出重复循环。一旦if语句满足而没有继续循环,有没有办法只返回myValue?

                   double myValue;

                   for (Map.Entry<Double, String> entry : treeMap1.entrySet()) {
                             double key = entry.getKey();
             String value = entry.getValue();
                System.out.printf("%s : %s\n", key, value);
                            System.out.println("Current value is: " + value);

                  //Locate specific values
              for (int pos=0; pos<treeMap1.size(); pos++) {

                 if (value.contains("abc")) 
                  { myValue = (double) 1/pos+1;
                   System.out.println("Current value is: " + value);
                   System.out.println("Current pos value is: " + pos);
                   System.out.println("Current my value is: " + myValue);}

         } }

2 个答案:

答案 0 :(得分:0)

一旦满足条件,只需使用break关键字退出for循环:

    for (int pos=0; pos<treeMap1.size(); pos++) {

             if (value.contains("abc")) 
              { myValue = (double) 1/pos+1;
               System.out.println("Current value is: " + value);
               System.out.println("Current pos value is: " + pos);
               System.out.println("Current my value is: " + myValue);
               break; // break the for loop
              }

     }

答案 1 :(得分:0)

感谢您的提示。以下是经过修订的Java类,它现在正在运行!

   import java.util.Map;

      public class MyValueCalculate {
      public static double mrr (Map<Double, String> map, String relSent) {
           int pos=0;
           double myValue = 0.0;
           for (Map.Entry<Double, String> entry : map.entrySet()) {
            pos = pos + 1;
            String value = entry.getValue();
           //System.out.println("Current value is: " + value);

      if (value.contains(relSent)) {
         myValue = (double) 1/pos;
         System.out.println("Current pos value is: " + pos);
         System.out.println("Current myValue is: " + myValue);
         break;
         } }
         return myValue;
         } }