gpt4 book ai didi

java - 找到Hashmap中的几个最大值

转载 作者:行者123 更新时间:2023-12-02 01:44:13 27 4
gpt4 key购买 nike

请您帮我找出为什么此代码只显示一个姓氏,我需要显示所有具有最大值的人我进行了测试,发现它找到了最大值,进行了比较,但只显示了一个姓氏

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

最佳答案

您应该使用.equals()而不是==来比较数字对象:

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

关于java - 找到Hashmap中的几个最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53944789/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com