java8-Lambda中比较器Comparator的使用

此教程旨在让读者学会使用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

    原文作者:石奈子
    原文地址: https://blog.csdn.net/u014042066/article/details/76248692
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞