Obtaining key associated with corresponding maximum value in a Map(TreeMap/HashMap)

前端 未结 2 437
萌比男神i
萌比男神i 2021-01-22 14:22

I have written the below code to find out the key(String) that has the maximum value(Integer) using TreeMap in JAVA.

public static void maxprofitItem(int[] costs         


        
相关标签:
2条回答
  • 2021-01-22 15:20

    You seem to be asking if using TreeMap instead of HashMap will give you a simpler way to find the key corresponding to the largest value/

    The answer to that is ... unfortunately ... No.

    0 讨论(0)
  • 2021-01-22 15:27

    The trick is that you can find maximum value together with its key by providing Comparator that compares entries by value.

    Comparator<Map.Entry<String, Integer>> byValue = Map.Entry.comparingByValue();
    Map.Entry<String, Integer> maxEntry = Collections.max(map.entrySet(), byValue);
    System.out.println("Maximum value is " + maxEntry.getValue());
    System.out.println("And it is for " + maxEntry.getKey());
    

    Or using new stream API

    map.entrySet().stream()
        .max(Map.Entry.comparingByValue())
        .ifPresent(maxEntry -> {
            System.out.println("Maximum value is " + maxEntry.getValue());
            System.out.println("And it is for " + maxEntry.getKey());
        });
    
    0 讨论(0)
提交回复
热议问题