java8-Lambda中比較器Comparator的使用

石奈子發表於2017-07-28

此教程旨在讓讀者學會使用lambda並結合Comparator進行集合排序操作

  • 典型的比較器示例
Comparator<Developer> byName = new Comparator<Developer>() {
    @Override
    public int compare(Developer o1, Developer o2) {
        return o1.getName().compareTo(o2.getName());
    }
};
  • 等價的Lambda的方式
Comparator<Developer> byName =
    (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());

不使用Lambda的排序

假如我們要通過Developer 物件的年齡進行排序,通常情況下我們使用Collections.sort,new個匿名Comparator 類,類似下面這種:

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

public class TestSorting {

    public static void main(String[] args) {

        List<Developer> listDevs = getDevelopers();

        System.out.println("Before Sort");
        for (Developer developer : listDevs) {
            System.out.println(developer);
        }

        //sort by age
        Collections.sort(listDevs, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        System.out.println("After Sort");
        for (Developer developer : listDevs) {
            System.out.println(developer);
        }

    }

    private static List<Developer> getDevelopers() {

        List<Developer> result = new ArrayList<Developer>();

        result.add(new Developer("ricky", new BigDecimal("70000"), 33));
        result.add(new Developer("alvin", new BigDecimal("80000"), 20));
        result.add(new Developer("jason", new BigDecimal("100000"), 10));
        result.add(new Developer("iris", new BigDecimal("170000"), 55));

        return result;

    }

}

輸出結果:

Before Sort
Developer [name=ricky, salary=70000, age=33]
Developer [name=alvin, salary=80000, age=20]
Developer [name=jason, salary=100000, age=10]
Developer [name=iris, salary=170000, age=55]

After Sort
Developer [name=jason, salary=100000, age=10]
Developer [name=alvin, salary=80000, age=20]
Developer [name=ricky, salary=70000, age=33]
Developer [name=iris, salary=170000, age=55]

當比較規則發生變化時,你需要再次new個匿名Comparator 類:

    //sort by age
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getAge() - o2.getAge();
        }
    });

    //sort by name
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    //sort by salary
    Collections.sort(listDevs, new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o1.getSalary().compareTo(o2.getSalary());
        }
    });

這樣也可以,不過你會不會覺得這樣有點怪,因為其實不同的只有一行程式碼而已,但是卻需要重複寫很多程式碼?

通過lambda進行排序

在java8中,List介面直接提供了排序方法, 所以你不需要使用Collections.sort

    //List.sort() since Java 8
    listDevs.sort(new Comparator<Developer>() {
        @Override
        public int compare(Developer o1, Developer o2) {
            return o2.getAge() - o1.getAge();
        }
    });

Lambda 示例


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class TestSorting {

    public static void main(String[] args) {

        List<Developer> listDevs = getDevelopers();

        System.out.println("Before Sort");
        for (Developer developer : listDevs) {
            System.out.println(developer);
        }

        System.out.println("After Sort");

        //lambda here!
        listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());

        //java 8 only, lambda also, to print the List
        listDevs.forEach((developer)->System.out.println(developer));
    }

    private static List<Developer> getDevelopers() {

        List<Developer> result = new ArrayList<Developer>();

        result.add(new Developer("ricky", new BigDecimal("70000"), 33));
        result.add(new Developer("alvin", new BigDecimal("80000"), 20));
        result.add(new Developer("jason", new BigDecimal("100000"), 10));
        result.add(new Developer("iris", new BigDecimal("170000"), 55));

        return result;

    }

}

輸出結果:

Before Sort
Developer [name=ricky, salary=70000, age=33]
Developer [name=alvin, salary=80000, age=20]
Developer [name=jason, salary=100000, age=10]
Developer [name=iris, salary=170000, age=55]

After Sort
Developer [name=jason, salary=100000, age=10]
Developer [name=alvin, salary=80000, age=20]
Developer [name=ricky, salary=70000, age=33]
Developer [name=iris, salary=170000, age=55]

更多的Lambda 例子

  • 根據年齡

        //sort by age
        Collections.sort(listDevs, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getAge() - o2.getAge();
            }
        });
    
        //lambda
        listDevs.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());
    
        //lambda, valid, parameter type is optional
        listDevs.sort((o1, o2)->o1.getAge()-o2.getAge());
  • 根據名字

        //sort by name
        Collections.sort(listDevs, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
    
        //lambda
        listDevs.sort((Developer o1, Developer o2)->o1.getName().compareTo(o2.getName()));
    
        //lambda
        listDevs.sort((o1, o2)->o1.getName().compareTo(o2.getName()));
  • 根據薪水

        //sort by salary
        Collections.sort(listDevs, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getSalary().compareTo(o2.getSalary());
            }
        });
    
        //lambda
        listDevs.sort((Developer o1, Developer o2)->o1.getSalary().compareTo(o2.getSalary()));
    
        //lambda
        listDevs.sort((o1, o2)->o1.getSalary().compareTo(o2.getSalary()))
  • 倒序

    • 正常排序

          Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());
          listDevs.sort(salaryComparator);
    • 倒序

        Comparator<Developer> salaryComparator = (o1, o2)->o1.getSalary().compareTo(o2.getSalary());
        listDevs.sort(salaryComparator.reversed());

翻譯

ricky 20170728

交流群:244930845

相關文章