在Map中获取与相应最大值关联的键(TreeMap / HashMap) [英] Obtaining key associated with corresponding maximum value in a Map(TreeMap/HashMap)

查看:194
本文介绍了在Map中获取与相应最大值关联的键(TreeMap / HashMap)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了下面的代码,用JAVA中的TreeMap来找出具有最大值(Integer)的键(String)。

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

(int i = 0; i< item.length; i ++){
profit [i] = sales [i] * prices [i] -costs [i] * sales [一世];
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();
整数值=(整数)map.get(key);

System.out.println(Key:+ key +,Value:+ value);如果(!map.isEmpty()){
System.out.println(最大值为+(Collections.max(map .values())));
System.out.println(这是为了);
maxvalue = Collections.max(map.values()); (Entry< String,Integer> entry:map.entrySet()){
if(entry.getValue()== maxvalue){
System.out.println(entry.getKey ());
休息;
}
}
}

其他{
System.out.println(这次出售没有利润);
}
}

maxprofitItem方法获取下面的参数作为参数。 / p>

传递成本值
{100,120,150,1000}
传递价格值
{110,110,200,2000}
传递销售值
{20,100,50,3}
传递项目值
{TV,图形卡,外部硬盘,显示器} $ /

该方法计算利润并将项目(Key)和利润(Value)放入TreeMap中。并且TreeMap如下所示。

键:监视器,值:3000



键:外部硬盘,值:2500

键: TV,Value:200

TreeMap和HashMap以相同的方式放置键/值对组合。
有没有更好的方法来使用TreeMap来查找与最大值关联的键,因为它在这方面与HashMap的操作方式相同。



提前致谢

解决方案

诀窍是,您可以通过提供比较器,按值比较条目。

 比较器< Map.Entry< String,Integer>> byValue = Map.Entry.comparingByValue(); 
Map.Entry< String,Integer> maxEntry = Collections.max(map.entrySet(),byValue);
System.out.println(最大值是+ maxEntry.getValue());
System.out.println(它用于+ maxEntry.getKey());

或者使用新的流API

<$ p $ ()。
.max(Map.Entry.comparingByValue())
.ifPresent(maxEntry - > {
System。p> map.entrySet() out.println(最大值是+ maxEntry.getValue());
System.out.println(它是为+ maxEntry.getKey());
});


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.

解决方案

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());
    });

这篇关于在Map中获取与相应最大值关联的键(TreeMap / HashMap)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆