温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java8怎么用Lambda表达式给List集合排序

发布时间:2021-11-19 16:03:38 来源:亿速云 阅读:352 作者:iii 栏目:编程语言

这篇文章主要介绍“Java8怎么用Lambda表达式给List集合排序”,在日常操作中,相信很多人在Java8怎么用Lambda表达式给List集合排序问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Java8怎么用Lambda表达式给List集合排序”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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的comparingComparator<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));

到此,关于“Java8怎么用Lambda表达式给List集合排序”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI