jdk1.8-map根據value排序,取前n位(及簡)
阿新 • • 發佈:2019-01-05
public static void main(String[] args) { Map<String,Integer> mapRepeat = new HashMap<>(); mapRepeat.put("aa", 1); mapRepeat.put("bb", 45); mapRepeat.put("cc", 32); mapRepeat.put("dd", 226); mapRepeat.put("ee", 16); mapRepeat.put("ff", 320); mapRepeat.put("gg", 99); Map<String,Integer> mapRepeat1 = new HashMap<>(); mapRepeat1.put("aa", 1); mapRepeat1.put("bb", 5); //.sorted標籤,對map根據value排序
//.map方法把map的key轉成set
//.subList取前n位,下圖(0,5位)
//.retainAll(拿key-set,去與map碰撞),判斷交集並覆蓋之前的list,取出相交個數
//list的value就是相交的 key,如需value取出即可
List<String> mobileList = mapRepeat.entrySet().stream() .sorted((Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) -> o2.getValue() - o1.getValue()) .map(entry -> entry.getKey()).collect(Collectors.toList()) .subList(0, 5); mobileList.retainAll(mapRepeat1.keySet()); System.out.println(JSON.toJSONString(mobileList.size())); }