Java8比较器(Lamdba)

1、首先构造一个实体以便示例使用

public class Developer {

    private String name;

    private BigDecimal salary;

    private int age;

    public Developer(String name, BigDecimal salary, int age) {
        this.name = name;
        this.salary = salary;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Developer{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", age=" + age +
                '}';
    }
}

 

2、在Java8之前排序的方式

public class TestSorting {

    public static void main(String[] args) {

        List<Developer> listDevs = getDevelopers();

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

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

    private static List<Developer> getDevelopers() {

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

        result.add(new Developer("mkyong", 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("10000"), 23));

        return result;
    }
}

 

3、在Java8使用Lamdba排序

public class TestSortingLamdba {

public static void main(String[] args) {

List<Developer> listDevs = getDevelopers();

listDevs.sort((Developer o1, Developer o2) -> o1.getAge() - o2.getAge());
listDevs.forEach(System.out::println);
System.out.println("----------------");

listDevs.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
listDevs.forEach(System.out::println);
System.out.println("----------------");

listDevs.sort(Comparator.comparing(Developer::getSalary));
listDevs.forEach(System.out::println);
System.out.println("----------------");

listDevs.sort(Comparator.comparing(Developer::getSalary).reversed());
listDevs.forEach(System.out::println);
}

private static List<Developer> getDevelopers() {

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

result.add(new Developer("mkyong", 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("10000"), 23));

return result;
}
}

 

posted @ 2019-02-23 00:30  风坤  阅读(1727)  评论(0编辑  收藏  举报