首页 > 解决方案 > 在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();
    }

标签: javahashmapmax

解决方案


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

推荐阅读