对map中的value进行倒序排序并且取第一个

547 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

引⾔

最近⼩编⾃⼰⼀个⼈在负责⼀个项⽬的后台开发,其中有⼀部分是统计相关的功能,所以需要⼀些排序或者分组的操作,之前这种操作⼩编

觉得还是⽐较⿇烦的,虽热有⼀些现成的⼯具类,但是⼯具类的写法也是⽐较复杂的,但是如果使⽤java8 stream流的话就⽐较简单了,

并且代码量会⼤⼤的减少,下⾯总结⼏个对map的操作。

1、map 根据value排序

Map map =new HashMap<>(); 
map.put("one", 0.08); 
map.put("two", 0.1); 
map.put("three", 0.2); 
map.put("four", 0.91);

上⾯是项⽬中的⼀个中间结果,我们需要对这个map根据value值倒序排序并且取第一个,下⾯给出⼯具类:

public<K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map){
    Map<K, V> result=new LinkedHashMap<>();
    map.entrySet().stream()
        .sorted(Map.Entry.<K, V>comparingByValue().reversed()).limit(1)
        .forEachOrdered(e->result.put(e.getKey(),e.getValue()));
    return result;
}

当然如果我们想根据map的key进⾏排序,需要对上⾯的⼯具类进⾏⼩⼩的修改,代码如下:

public <K extends Comparable<? super K>, V> Map sortByKey(Map<K,V> map) {
    Map<K,V> result = new LinkedHashMap<>();
    map.entrySet().stream()
        .sorted(Map.Entry.<K, V>comparingByKey().reversed())
        .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
}

我们可以看到,如果我们需要根据key排序,就需要让key 继承 Comparable ,也就说我们需要对待排序的字段继承 Comparable接⼝。

另⼀个问题就是,上⾯的这种写法排序效果是 降序排序,如果我们需要升序排序的话,只需要将上⾯的.reversed()关键字限制去掉即可。

public <K extends Comparable<? super K>, V> Map sortByKey(Map<K,V> map) {
    Map<K,V> result = new LinkedHashMap<>();
    map.entrySet().stream()
        .sorted(Map.Entry.<K, V>comparingByKey()
        .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
}

综合写法

/**
 * map排序
 *
 * @param map  要排序的目标数组
 * @param isKey  是否是按key进行排序
 * @param isDesc  是否是降序
 * @param <K>
 * @param <V>
 * @return
 */
public<K extends Comparable<? super K>, V extends Comparable<? super V>> Map<K, V> sortMap(Map<K, V> map,boolean isKey,boolean isDesc){

    Map<K, V> result=new LinkedHashMap<>();
    if(isKey){
        if(isDesc){
        map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
        .forEachOrdered(e->result.put(e.getKey(),e.getValue()));
        }else{
        map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey())
        .forEachOrdered(e->result.put(e.getKey(),e.getValue()));
        }
        return result;
    }else{
        if(isDesc){
            map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())//根据value降序排序
            .forEachOrdered(e->result.put(e.getKey(),e.getValue()));
        }else{
            map.entrySet().stream()
            .sorted(Map.Entry.<K, V>comparingByValue()//根据value升序排序
            ).forEachOrdered(e->result.put(e.getKey(),e.getValue()));
        }
        return result;
    }
}