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

作者:寻找风口的猪 时间:2023-02-05 17:27:09 

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实战》

来源:https://www.cnblogs.com/happyflyingpig/p/9090598.html

标签:Java8,List,集合排序
0
投稿

猜你喜欢

  • Android完整Socket解决方案

    2023-12-22 14:42:40
  • C#清除WebBrowser中Cookie缓存的方法

    2022-01-13 20:01:08
  • gateway网关与前端请求跨域问题的解决方案

    2022-09-20 01:30:44
  • Java并发编程学习之Unsafe类与LockSupport类源码详析

    2022-10-21 19:07:01
  • 深入java事件注册的应用分析

    2022-07-12 01:37:55
  • mybatis中<choose>标签的用法说明

    2023-07-22 19:37:27
  • 解决Spring Batch框架job任务只跑一次的问题

    2023-01-07 00:13:53
  • Java创建子线程的两种方法

    2023-11-24 07:00:05
  • Android百度地图实现搜索和定位及自定义图标绘制并点击时弹出泡泡

    2023-08-30 21:30:38
  • 一文带你深入了解Java泛型

    2022-02-10 05:38:02
  • SpringBoot 如何整合 ES 实现 CRUD 操作

    2022-03-24 03:10:31
  • SpringBoot 使用Mybatis分页插件实现详解

    2023-03-06 22:34:19
  • C++指向类成员函数的指针详细解析

    2022-03-05 04:50:28
  • Java实战之在线租房系统的实现

    2022-09-29 04:44:18
  • Java使用动态规划算法思想解决背包问题

    2022-12-02 03:53:49
  • android 自定义Android菜单背景的代码

    2022-06-23 08:54:40
  • java定时任务Timer和TimerTask使用详解

    2023-07-13 00:29:33
  • Java 如何使用Feign发送HTTP请求

    2023-05-10 15:04:08
  • 详解Android App中使用VideoView来实现视频播放的方法

    2022-05-01 00:20:11
  • Springboot项目打war包docker包找不到resource下静态资源的解决方案

    2022-01-01 07:03:55
  • asp之家 软件编程 m.aspxhome.com