Comparator 外部比較器使用介紹

定義測試model類:

public class User {
    private Integer age;

    public User(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

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

 

測試類:

此處使用最簡單的匿名內部類實現重寫比較函數,虛擬參數爲o1,o2,返回值爲 o1-o2(也可以返回 JDk默認的比較參數 -1,0,1用來比較大小),這樣就實現了升序排序。 


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Comparator_test {

    public static void main(String[] args) {
        List<User> integerList = new ArrayList<User>() {{
            add(new User(1));
            add(new User(5));
            add(new User(3));

        }};

        Collections.sort(integerList, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        Collections.reverse(integerList);

        integerList.forEach(System.out::println);

    }
}

//使用lambda表達式代替匿名內部類,查看Compatator 知道,在JDk 1.8 中此接口添加了

@FunctionalInterface,成爲了一個函數式接口,而lamda可以用表達式或函數體表示,因此這裏可以使用lambda簡化代碼。

 (o1, o2) -> o1.getAge()-o2.getAge() ,此處,定義了兩個參數,功能是返回兩者的差值,作用與匿名內部類相同。

 

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Comparator_test {

    public static void main(String[] args) {
        List<User> integerList = new ArrayList<User>() {{
            add(new User(1));
            add(new User(5));
            add(new User(3));

        }};

        Collections.sort(integerList, (o1, o2) -> o1.getAge()-o2.getAge());
        Collections.reverse(integerList);

        integerList.forEach(System.out::println);

    }
}

 

//使用函數代替lambda

查看

Comparator<T>源碼可知,新添加了返回比較器的方法,Comparator.comparingInt(User::getAge)

源碼如下:

    /**
     * Accepts a function that extracts an {@code int} sort key from a type
     * {@code T}, and returns a {@code Comparator<T>} that compares by that
     * sort key.
     *
     * <p>The returned comparator is serializable if the specified function
     * is also serializable.
     *
     * @param  <T> the type of element to be compared
     * @param  keyExtractor the function used to extract the integer sort key
     * @return a comparator that compares by an extracted key
     * @see #comparing(Function)
     * @throws NullPointerException if the argument is null
     * @since 1.8
     */
    public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
    }

 參數還是函數式接口,方法體返回的功能即上個方法中lambda表達式的功能,因此這裏可以再次化簡我們的代碼:


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Comparator_test {

    public static void main(String[] args) {
        List<User> integerList = new ArrayList<User>() {{
            add(new User(1));
            add(new User(5));
            add(new User(3));

        }};

        Collections.sort(integerList, Comparator.comparingInt(User::getAge));
        Collections.reverse(integerList);

        integerList.forEach(System.out::println);

    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章