简体   繁体   English

在Java中索引Treemap值

[英]Index a Treemap value in java

I have a Treemap in pairs and need to find a specific value, locate its position (index) and do some calculations. 我有一对成对的Treemap,需要找到一个特定值,找到其位置(索引)并进行一些计算。 The for loop did find the specific value, but it loops repeatedly based on System.out.println outputs. for循环确实找到了特定的值,但是它基于System.out.println输出反复循环。 Is there any way just to return myValue once the if statement satisfies without continuing looping? 如果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);}

         } }

Simply come out of the for loop using break keyword once condition is met: 满足条件后,只需使用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
              }

     }

Thank you for the tips. 感谢您的小费。 The following is a revised Java class and it's now working! 以下是经过修订的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;
         } }  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM