從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