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

标签 java hashmap max

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

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/

相关文章:

Java 二叉树/访问者模式

java - 集合 sort(List<T>,Comparator<? super T>) 方法示例

java - 为什么 HashSet 的内部实现会创建虚拟对象以作为值插入 HashMap 而不是插入空值?

Java,确定 HashMap 中是否有任何值与值匹配的最快方法?

Java ConcurrentHashMap 损坏的值

mysql 最大严格模式

Array对象数据的Java、ErroMax和Min?

java - MongoCursor 没有 count() 方法?

java - Spring mvc @RequestBody如何用@EmbeddedId解析JPA实体

mysql - 从另一个表创建一个包含计数/最高/最低的表