java - 在Hashmap中找到几个最大值
问题描述
请您帮我找出为什么这段代码只显示一个姓氏,我需要显示所有具有最大值的人我测试并看到它找到最大值,它比较,但只显示一个姓氏
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
TreeMap<String, Double> map = new TreeMap<>();
ArrayList<String> sArray = new ArrayList<>();
while (reader.ready()) {
String st = reader.readLine();
sArray.add(st);
}
for (String s : sArray) {
String[] array = s.split(" ");
String name = array[0];
double price = Double.parseDouble(array[1]);
if (map.containsKey(name)) {
price = price + map.get(name);
}
map.put(name, price);
}
Double maxValueInMap = (Collections.max(map.values())); // This will return max value in the Hashmap
System.out.println(maxValueInMap);
for (Map.Entry<String, Double> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue() + " | " + (entry.getValue()==maxValueInMap));// Itrate through hashmap
if (entry.getValue() == maxValueInMap) {
System.out.println(entry.getKey()); // Print the key with max value
}
}
reader.close();
}
解决方案
You should compare number objects with .equals()
instead of ==
:
for (Map.Entry<String, Double> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue() + " | " + (entry.getValue().equals(maxValueInMap)));// Itrate through hashmap
if (entry.getValue().equals(maxValueInMap)) {
System.out.println(entry.getKey()); // Print the key with max value
}
}
推荐阅读
- android - RNFirebase 通知问题显示图标
- java - 在 Eclipse 中无法启动 tomcatv9.0
- c++ - 消息框在 WM_COMMAND 中不起作用!(WIN32 API)
- scanf - 使用 x86_64 NASM 扫描中的段错误
- javascript - 如何使用javascript防止屏幕休眠
- spring-integration - spring集成中如何在运行时解析jms出站目标队列,
- c - 为什么八进制序列 '\0101' 不等于十进制 65?
- mongodb - mongodb 将字段分组到列表中
- c++ - 什么是“初始换档状态”?
- websphere - WebSphere - 通过 Jython 将模块映射到目标