Obtendo a chave associada ao valor máximo correspondente em um Mapa (TreeMap / HashMap)

Eu escrevi o código abaixo para descobrir a chave (String) que tem o valor máximo (Inteiro) usando o TreeMap em JAVA.

public static void maxprofitItem(int[] costs, int[] prices, int[] sales,String[] items) {
    TreeMap<String,Integer>map=new TreeMap<String,Integer>();
    int[] profits=new int[items.length];
    int maxvalue;

    for(int i=0;i<items.length;i++){
        profits[i]=sales[i]*prices[i]-costs[i]*sales[i];
        if(profits[i]>0){
            map.put(items[i],profits[i]);
        }
    }

    Set setOfKeys = map.keySet();
    Iterator iterator = setOfKeys.iterator();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        Integer value = (Integer)map.get(key);

        System.out.println("Key: "+ key+", Value: "+ value);
    }


    if(!map.isEmpty()){
        System.out.println("The maximum value is "+(Collections.max(map.values())));
        System.out.println("And it is for");
        maxvalue=Collections.max(map.values());
        for (Entry<String, Integer> entry : map.entrySet()) {  
            if (entry.getValue()==maxvalue) {
                System.out.println(entry.getKey());
                break;
            }
        }   
    }

    else{
        System.out.println("There are no profits in this sale");
    }
}

O método maxprofitItem obtém os parâmetros abaixo como argumentos.

Passe os valores de custos {100,120,150,1000} Passe os valores de preços {110,110,200,2000} Passe os valores de vendas {20,100,50,3} Passe os valores dos itens {"TV", "Placa gráfica", "Disco rígido externo", " Monitor"}

O método calcula os lucros e coloca os itens (Chave) e lucros (Valor) no TreeMap. E o TreeMap se parece com abaixo.

Chave: Monitor, Valor: 3000

Chave: Disco rígido externo, Valor: 2500

Chave: TV, Valor: 200

TreeMap e HashMap colocam a combinação de pares chave / valor da mesma maneira. Existe uma maneira melhor de usar o TreeMap inorder para descobrir a chave associada ao valor máximo, uma vez que opera da mesma maneira que o HashMap a esse respeito.

Desde já, obrigado.

questionAnswers(2)

yourAnswerToTheQuestion