1. 程式人生 > >Comparator泛型排序方法,適用於多種型別,函數語言程式設計

Comparator泛型排序方法,適用於多種型別,函數語言程式設計


import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Desc
 **/
public class ComparatorT {

    public static void main(String[] args) {
        ComparatorT comparatorT = new ComparatorT();
//        comparatorT.f1();
        comparatorT.f2();
    }

    /**
     * 原始方法
     */
    public void f1() {
        List<String> stringList = new ArrayList<String>() {{
            add("c");
            add("b");
            add("a");
        }};
        stringList.sort(((o1, o2) -> o1.compareTo(o2)));
        System.out.println(stringList);//[a, b, c]

        List<Long> longList = new ArrayList<Long>() {{
            add(12L);
            add(10L);
            add(22L);
        }};
        longList.sort(((o1, o2) -> o1.compareTo(o2)));
        System.out.println(longList);//[10, 12, 22]
    }

    /**
     * 使用自定義排序函式
     */
    public void f2() {
        List<String> stringList = new ArrayList<String>() {{
            add("c");
            add("b");
            add("a");
        }};
        stringList = sortFunction(stringList, (o1, o2) -> o1.compareTo(o2));
        System.out.println(stringList);//[a, b, c]

        List<Long> longList = new ArrayList<Long>() {{
            add(12L);
            add(10L);
            add(22L);
        }};
        longList = sortFunction(longList, (o1, o2) -> o1.compareTo(o2));
        System.out.println(longList);//[10, 12, 22]

        List<UserClass> userClassList = new ArrayList<UserClass>() {{
            add(new UserClass(11, "c"));
            add(new UserClass(14, "b"));
            add(new UserClass(10, "a"));
        }};
        userClassList = sortFunction(userClassList, (u1, u2) -> u1.getAge().compareTo(u2.getAge()));
        System.out.println(JSON.toJSONString(userClassList));//[{"age":10,"name":"a"},{"age":11,"name":"c"},{"age":14,"name":"b"}]
    }

    /**
     * 泛型  排序函式
     * @param tList
     * @param comparator
     * @param <T>
     * @return
     */
    public <T> List<T> sortFunction(List<T> tList, Comparator<T> comparator) {
        return tList.stream().sorted(comparator).collect(Collectors.toList());
    }
}


class UserClass {

    private Integer age;
    private String name;


    public UserClass(Integer age, String name) {
        this.age = age;
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}