参考:https://www.cnblogs.com/invoker-/p/7709411.html

1.准备

实体类

import lombok.AllArgsConstructor;
import lombok.Data;


@Data
@AllArgsConstructor
public class UserObj {
    private String name;
    private Integer age;
    private Integer credits;
}

测试类

package com.pu.helloworld;

import org.assertj.core.util.Lists;

import java.util.List;

public class TestJava8 {
    public static void main(String[] args) {
        List<UserObj> userObjs = Lists.newArrayList(
                new UserObj("aa",9,70),
                new UserObj("aa",2,50),
                new UserObj("aa",6,60),
                new UserObj("ee",3,80),
                new UserObj("dd",5,70),
                new UserObj("ee",6,99),
                new UserObj("ff",9,73)
        );

    }
}

2.按年龄排序

这里使用lambda表达式来代替匿名内部类,并且使用list接口下的sort方法(java8新增加),再链式输出

   userObjs.sort(((o1, o2) -> o1.getAge()-o2.getAge()));
   userObjs.forEach(userObj -> System.out.println(userObj));

当然还可以通过方法引用进一步的简化,这里使用Comparator下的comparingInt进行排序,使用User::getAge获得年龄,默认从小到大正向排序

userObjs.sort(Comparator.comparingInt(UserObj::getAge));
userObjs.forEach(System.out::println);

输出:

UserObj(name=aa, age=2, credits=50)
UserObj(name=ee, age=3, credits=80)
UserObj(name=dd, age=5, credits=70)
UserObj(name=aa, age=6, credits=60)
UserObj(name=ee, age=6, credits=99)
UserObj(name=aa, age=9, credits=70)
UserObj(name=ff, age=9, credits=73)

3.按年龄倒序

在比较器后面增加reversed即可,链式调用是java8的风格之一,同样是阅读性,原先的匿名内部类方法不仅阅读困难,一个简单的倒序也需要先去观察o2-o1还是o1-o2才能得出,而Java8的方法不仅代码简洁,可读性还很高,compare getAge读出是通过年龄进行排序,reversed读出是倒序。

userObjs.sort(Comparator.comparingInt(UserObj::getAge).reversed());
userObjs.forEach(System.out::println);

4.按姓名,年龄,积分排序

  • 在这里我们使用比较器的thenComparing实现链式调用
 userObjs.sort(Comparator.comparing(UserObj::getName)
                .thenComparing(UserObj::getAge)
                .thenComparing(UserObj::getCredits)
        );
        userObjs.forEach(System.out::println);

输出:

UserObj(name=aa, age=2, credits=50)
UserObj(name=aa, age=6, credits=60)
UserObj(name=aa, age=9, credits=70)
UserObj(name=dd, age=5, credits=70)
UserObj(name=ee, age=3, credits=80)
UserObj(name=ee, age=6, credits=99)
UserObj(name=ff, age=9, credits=73)

按姓名升,年龄降,积分升排序

 userObjs.sort(Comparator.comparing(UserObj::getName)
                .thenComparing(UserObj::getAge,((o1, o2) -> o2-o1))
                .thenComparing(UserObj::getCredits)
        );

实上 o2 - o1 这样的代码还是有一些命令式的风格,即包含了具体的实现过程(o2 -o1这样的代码),thenComparaing方法可以直接接受一个排序器,因此我们只要直接将倒序的排序器当做参数传入即可,代码如下

        userObjs.sort(Comparator.comparing(UserObj::getName)
                .thenComparing(Comparator.comparing(UserObj::getAge).reversed())
                .thenComparing(UserObj::getCredits)
        );

 

posted on 2019-09-06 19:07  pu20065226  阅读(1757)  评论(0编辑  收藏  举报