lambda表达式之集合排序工具类

使用java8的函数式接口简化集合排序中Compartor的写法

/**
 * 集合排序工具类
 * 函数式接口简化代码
 */
public class CollectionSort {
    public static void main(String[] args) {
        Map dataMap = new HashMap<>();
        dataMap.put("c",2);
        dataMap.put("a",7);
        dataMap.put("f",5);
        dataMap.put("p",9);
        dataMap.put("z",8);
        Map newMap = sortValue(dataMap);
        System.out.println(newMap);
    }
    public static  Map sortKey(Map dataMap){
        List> entryList = new ArrayList<>(dataMap.entrySet());
        Collections.sort(entryList,(m1,m2)->m1.getKey().compareTo(m2.getKey()));
        return SortList(entryList);
    }

    public static  Map sortKeyDesc(Map dataMap){
        List> entryList = new ArrayList<>(dataMap.entrySet());
        Collections.sort(entryList,(m1,m2)->m2.getKey().compareTo(m1.getKey()));
        return SortList(entryList);
    }

    public static  Map sortValue(Map dataMap){
        List> entryList = new ArrayList<>(dataMap.entrySet());
        Collections.sort(entryList,(m1,m2)->m1.getValue().compareTo(m2.getValue()));
        return SortList(entryList);
    }

    public static  Map sortValueDesc(Map dataMap){
        List> entryList = new ArrayList<>(dataMap.entrySet());
        Collections.sort(entryList,(m1,m2)->m2.getValue().compareTo(m1.getValue()));
        return SortList(entryList);
    }

    private static  Map SortList(List> entryList) {
        Iterator> it = entryList.iterator();
        Map tempMap = new LinkedHashMap<>();
        while(it.hasNext()){
            Map.Entry mapEntry = it.next();
            tempMap.put(mapEntry.getKey(),mapEntry.getValue());
        }
        return tempMap;
    }
}

 

你可能感兴趣的:(lambda)