幾種list排序方法


package com.lgx.jdk8.part02;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * Comparator比較器的使用
 */
public class TestComparator {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("nice", "to", "meet", "you");
 
        //升序排序,流的寫法
        //list.stream().sorted(Comparator.comparing(str -> str)).collect(Collectors.toList()).forEach(System.out::println);
 
        //升序排序,默認寫法
        /*Collections.sort(list);
        System.out.println("list = " + list);*/
 
        //自定義排序器,默認寫法
        /*Collections.sort(list, (item1, item2) -> item1.length() - item2.length()); //升序
        Collections.sort(list, (item1, item2) -> item2.length() - item1.length());   //降序
        System.out.println("list = " + list);*/
 
        //自定義排序器,Comparator寫法
        /*Collections.sort(list, Comparator.comparingInt(str -> str.length()));                       //升序
        Collections.sort(list, Comparator.comparingInt(str -> str.length()).reversed());              //降序,會報錯,因為編譯器在這里無法推斷str的類型為String,而是推斷出事一個Objcet
        Collections.sort(list, Comparator.comparingInt((String str) -> str.length()).reversed());*/   //降序,顯示的指定一個類型
 
        //自定義排序器,Comparator寫法2
        /*Collections.sort(list, Comparator.comparingInt(String::length));           //升序
        Collections.sort(list, Comparator.comparingInt(String::length).reversed());  //降序
        System.out.println("list = " + list);*/
 
        //直接調用list的排序方法,Collections.sort()本質還是調用list.sort方法
        /*list.sort(Comparator.comparingInt(String::length));             //升序
        list.sort(Comparator.comparingInt(String::length).reversed());    //降序*/
 
        /**兩層排序:先按照長度排序,再按照字符串順序**/
        //Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(String.CASE_INSENSITIVE_ORDER));   //不區分大小寫的排序
        //Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(String::compareTo));
        //Collections.sort(list, Comparator.comparingInt(String::length).thenComparing((item1, item2) -> item1.toLowerCase().compareTo(item2.toLowerCase())));
        //Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(Comparator.comparing(String::toLowerCase)));
        //Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())));
        Collections.sort(list, Comparator.comparingInt(String::length).thenComparing(Comparator.comparing(String::toLowerCase, Comparator.reverseOrder())).
                thenComparing(Comparator.reverseOrder()));//和上一個結果是一樣的,因為已經排好序了,最后一個就不起作用了
        System.out.println("list = " + list);
 
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM