一、适用场景:相对Map排序,想获取其中最大或最小值。
1、获取map集合里,获取 max(value)对应的key
1)、方式1
@Testpublic void MapInnerMaxValue() {HashMap<String, Integer> hashMap = new HashMap<>();hashMap.put("a", 10);hashMap.put("s", 36);hashMap.put("c", 88);hashMap.put("e", 27);hashMap.put("6", 100);Optional<String> maxValueKeyOptional = hashMap.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey);maxValueKeyOptional.ifPresent(key -> System.out.println("最大value对应的key是: " + key));}
输出
最大value对应的key是: 6
2)、方式二:通过TreeMap获取
单线程情况下,用TreeMap时间复杂度O(logn),性能较好,推荐。
@Testpublic void MapInnerMaxValue2() {Comparator<Integer> c=Comparator.comparingInt(Integer::intValue);TreeMap<Integer,String> treeMap= new TreeMap (c);treeMap.put( 10,"i:j");treeMap.put( 36,"s");treeMap.put(88,"c");treeMap.put( 27,"e");treeMap.put( 100,"i:j");log.info("max(value)={},key={}", treeMap.lastEntry().getKey(),treeMap.lastEntry().getValue());}输出:max(value)=100,key=i:j
3)、方式三:通过TreeMap获取
想保证并发安全,还要保持较好性能,ConcurrentSkipListMap就是很不错的选择,时间复杂度O(logn) ,推荐使用。
@Testpublic void MapInnerMaxValue3() {Comparator<Integer> c=Comparator.comparingInt(Integer::intValue);ConcurrentSkipListMap<Integer,String> skipMap= new ConcurrentSkipListMap (c);skipMap.put( 10,"i:j");skipMap.put( 36,"s");skipMap.put(88,"c");skipMap.put( 27,"e");skipMap.put( 100,"i:j");log.info("max(value)={},key={}", skipMap.lastEntry().getKey(),skipMap.lastEntry().getValue());}输出:
max(value)=100,key=i:j
待追加…