打印具有 5 个最高值的键

我有一个 HashMap 定义为:


Map<String, Double> data = new HashMap<String, Double>();

我正在尝试打印出具有最高 Double 值的 5 个字符串。我尝试通过对每个循环运行 5 次并保存最高值来做到这一点,同时我将整个 HashMap 迭代 5 次,但在 if 语句中出现空指针异常错误。


int highest = 0;

String highestkey;


 for(int i=0; i<5; i++){

     for(Map.Entry<String, Double> x : data.entrySet()){

        if(data.get(x) > highest){

           highestkey = x.getKey();

        }

     }

     System.out.println(highestkey);

     info_words.remove(highestkey);

  }

我的代码应该做的是在解析 HashMap 时跟踪最高的 Double 值,然后最终打印最高的键,然后将其删除,因此没有重复,然后再重复该过程 4 次,但它不能作为故意的


芜湖不芜
浏览 81回答 1
1回答

Helenr

尝试这个:&nbsp; &nbsp; &nbsp; &nbsp; Double highest = 0.0;&nbsp; &nbsp; &nbsp; &nbsp; String highestkey = "";&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 5; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (Map.Entry<String, Double> x : data.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (x.getValue() > highest) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; highest = x.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; highestkey = x.getKey();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(highestkey);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //remove highest here&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java