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


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM