JAVA8之Comparator特殊排序以及ComparatorUtils介绍

1,将数组按照自然顺序排序

public static void main(String[] args) {
        String[] array = {"G", "D", "E", "A", "C", "B", "F"};
        //并行流可以提高效率并在数据不超过1 << 13 == 8192时不会使用多线程执行 
        Arrays.parallelSort(array);
        System.out.println(com.alibaba.fastjson.JSONObject.toJSONString(array));
    }

结果为:["A","B","C","D","E","F","G"]

2,将数组按自然顺序降序,判断空指针,并置顶某个元素

public static void main(String[] args) {
        String[] array = {"G", "D",null, "E", "A", "C", "B", "F"};
        Arrays.parallelSort(array, ComparatorUtils.nullHighComparator((k1, k2) -> {
            if ("E".equals(k1)) {
                return -1;
            }
            if("E".equals(k2)){
                return 1;
            }
            return k2.compareToIgnoreCase(k1);
        }));
        System.out.println(com.alibaba.fastjson.JSONObject.toJSONString(array));
    }

结果为:["E","G","F","D","C","B","A",null]

ComparatorUtils 是apache提供的比较器工具类,nullHighComparator()可以判断空指针并将null数据放在数据末尾.nullLowComparator()同样可以判断空指针但是将null放在前面
提供一个仅供参考的实现

 public static void main(String[] args) {
        String[] array = {"G", "D",null, "E", "A", "C", "B", "F"};
        Comparator comparator = ComparatorUtils.nullHighComparator((k1, k2) -> {
            if ("E".equals(k1)) {
                return -1;
            }
            if ("E".equals(k2)) {
                return 1;
            }
            return k1.compareToIgnoreCase(k2);
        });
        comparator = ComparatorUtils.reversedComparator(comparator);
        Arrays.parallelSort(array, comparator);
        System.out.println(com.alibaba.fastjson.JSONObject.toJSONString(array));
    }

结果为:[null,"G","F","D","C","B","A","E"]

你可能感兴趣的:(JAVA)