Obtaining key associated with corresponding maximu

2020-04-14 07:03发布

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, 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");
    }
}

The method maxprofitItem gets the below parameters as arguments.

Pass the costs values {100,120,150,1000} Pass the prices values {110,110,200,2000} Pass the sales values {20,100,50,3} Pass the items values {"TV","Graphics card","External Hard disk","Monitor"}

The method calculates the profits and puts the items(Key) and profits(Value) in TreeMap.And the TreeMap looks like below.

Key: Monitor, Value: 3000

Key: External Hard disk, Value: 2500

Key: TV, Value: 200

TreeMap and HashMap puts the key/value pair combination in the same manner. Is there a better way to use TreeMap inorder to find out the key assocaited with the maximum value as it operates in the same manner as HashMap in this regard.

Thanks in advance.

2条回答
趁早两清
2楼-- · 2020-04-14 07:42

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());
    });
查看更多
Luminary・发光体
3楼-- · 2020-04-14 07:51

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.

查看更多
登录 后发表回答