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 stringList = new ArrayList() {{
            add("c");
            add("b");
            add("a");
        }};
        stringList.sort(((o1, o2) -> o1.compareTo(o2)));
        System.out.println(stringList);//[a, b, c]

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

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

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

        List userClassList = new ArrayList() {{
            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 
     * @return
     */
    public  List sortFunction(List tList, Comparator 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;
    }
}

以上基于jdk1.8

你可能感兴趣的:(Java,Comparator,泛型,排序,类型,函数式编程)