欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java8 用Lambda表达式给List集合排序的实现

时间:2021-04-28 08:06:50|栏目:JAVA代码|点击:

Lambda用到了JDK8自带的一个函数式接口Comparator<T>。

准备一个Apple类

public class Apple {
  private int weight;
  private String color;

  public Apple(){}

  public Apple(int weight) {
    this.weight = weight;
  }

  public Apple(int weight, String color) {
    this.weight = weight;
    this.color = color;
  }
  
  setters();getters();toString(); 
}

步骤一:

public class AppleComparator implements Comparator<Apple> {
  @Override
  public int compare(Apple o1, Apple o2) {
    return o1.getWeight() - o2.getWeight();
  }
}

步骤二:准备一个List集合

ArrayList<Apple> inventory = Lists.newArrayList(
        new Apple(10, "red"),
        new Apple(5, "red"),
        new Apple(1, "green"),
        new Apple(15, "green"),
        new Apple(2, "red"));

步骤三:顺序排序,三种方式

/**
 * 顺序排序
 */
// 1、传递代码,函数式编程
inventory.sort(new AppleComparator());
System.out.println(inventory);

// 2、匿名内部类
inventory.sort(new Comparator<Apple>() {
  @Override
  public int compare(Apple o1, Apple o2) {
    return o1.getWeight() - o2.getWeight();
  }
});

// 3、使用Lambda表达式
inventory.sort((a, b) -> a.getWeight() - b.getWeight());

// 4、使用Comparator的comparing
Comparator<Apple> comparing = comparing((Apple a) -> a.getWeight());
inventory.sort(comparing((Apple a) -> a.getWeight()));
//或者等价于
inventory.sort(comparing(Apple::getWeight));

步骤四:逆序排序

/**
 * 逆序排序
 */
// 1、 根据重量逆序排序
inventory.sort(comparing(Apple::getWeight).reversed()); 

步骤五:如果两个苹果一样重,就得再找一个条件来进行排序

// 2、如果两个苹果的重量一样重,怎么办?那就再找一个条件进行排序呗
inventory.sort(comparing(Apple::getWeight).reversed().thenComparing(Apple::getColor));

https://gitee.com/play-happy/base-project

参考:

【1】《Java8实战

上一篇:SpringBoot 利用thymeleaf自定义错误页面

栏    目:JAVA代码

下一篇:Spring Boot启动及退出加载项的方法

本文标题:Java8 用Lambda表达式给List集合排序的实现

本文地址:http://www.codeinn.net/misctech/110529.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有