Comparator简介与使用

Comparator简介与使用

    public static void main(String[] args) {
    
    

        List<String> strs = Stream.of("hello", "world", "hello world").collect(Collectors.toList());
        // 按照字母升序排序
//        Collections.sort(strs);
//        strs.forEach(System.out::println);
        // 按照字符串的长度排序 升序
        Collections.sort(strs, (o1, o2) -> o1.length() - o2.length());
        strs.forEach(System.out::println);
        // 简化写法
        strs.sort(Comparator.comparingInt(String::length));
        strs.forEach(System.out::println);
        // 按照字符串的长度排序 降序序
        Collections.sort(strs, (o1, o2) -> o2.length() - o1.length());
        strs.forEach(System.out::println);
        // 简化写法
        strs.sort(Comparator.comparingInt(String::length).reversed());
        strs.forEach(System.out::println);
        // Lambda写法 (类型推断 无法通过上下文推断出o的类型, 所以需要声明类型)
        strs.sort(Comparator.comparingInt((String o) -> o.length()).reversed());

        // -----------------------------
        // 按照字符串的长度 长度相等再按字母排序
        // thenComparing只要第一个比较器的 几个值得比较结果都是零(就是相同)  才会执行thenComparing
        // 也就是说之前的那个比较器能确定顺序 就用之前的那个比较器的结果 只有之前的比较器的结果而为零 才会执行thenComparing
        strs.sort(Comparator.comparingInt(String::length).thenComparing(String.CASE_INSENSITIVE_ORDER));

    }

猜你喜欢

转载自blog.csdn.net/weixin_43939924/article/details/111489028