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

所属分类: 软件编程 / java 阅读数: 29
收藏 0 赞 0 分享

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java Set简介_动力节点Java学院整理

Set最大的特性就是不允许在其中存放的元素是重复的。接下来通过本文给大家分享java set常用方法和原理分析,需要的的朋友参考下吧
收藏 0 赞 0 分享

Java Timezone类常见问题_动力节点Java学院整理

这篇文章主要介绍了Java Timezone类常见问题的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

javaWeb项目部署到阿里云服务器步骤详解

本篇文章主要介绍了javaWeb项目部署到阿里云服务器步骤详解,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

详解使用zxing库生成QR-Code二维码

这篇文章主要介绍了详解使用zxing库生成QR-Code二维码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

java实现对服务器的自动巡检邮件通知

这篇文章主要为大家详细介绍了java实现对服务器的自动巡检邮件通知,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java随机验证码生成实现实例代码

这篇文章主要介绍了java随机验证码生成实现实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

java读取txt文件代码片段

这篇文章主要为大家详细介绍了java读取txt文件的代码片段,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java连接mysql数据库的方法

这篇文章主要为大家详细介绍了java连接mysql数据库的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

java 算法之快速排序实现代码

这篇文章主要介绍了java 算法之快速排序实现代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

这篇文章主要介绍了详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多