首页 > 其他 > 详细

从map中取出最大或最小value对应的key---多种写法

时间:2019-04-22 21:54:23      阅读:1230      评论:0      收藏:0      [点我收藏+]
package com.yuwanlong.hashing;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author Yu Wanlong
 */

public class ValidAnagram {
  public static void main(String[] args) {
    Map<String, Double> map = new HashMap();
    map.put("1", 8.);
    map.put("2", 12.);
    map.put("3", 53.);
    map.put("4", 33.);
    map.put("5", 11.);
    map.put("6", 3.);
    map.put("7", 3.);
    map.put("8", 1.);
    //List<Entry<String,Integer>> list = new ArrayList(map.entrySet());
    //Collections.sort(list, (o1, o2) -> (o1.getValue() - o2.getValue()));
    String minKey = getMapMinOrMaxValueKey(map, "min");
    String maxKey = getMapMinOrMaxValueKey(map, "max");
    System.out.println(map.get(minKey));
    System.out.println(map.get(maxKey));
  }

  public static String getMapMinOrMaxValueKey(Map<String, Double> map, String choose) {
    List<Entry<String,Double>> list = new ArrayList(map.entrySet());
    Collections.sort(list, (o1, o2) -> (o1.getValue().intValue() - o2.getValue().intValue()));
    String key = "";
    if (choose.equals("min")) {
      key = list.get(0).getKey();
    } else if (choose.equals("max")) {
      key = list.get(list.size() - 1).getKey();
    }
    return key;
  }
}

 

从map中取出最大或最小value对应的key---多种写法

原文:https://www.cnblogs.com/yuwanlong/p/10753132.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!