java list对象排序函数_java List对象排序

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

准备一个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 {

@Override

public int compare(Apple o1, Apple o2) {

return o1.getWeight() - o2.getWeight();

}

}

步骤二:准备一个List集合

ArrayList 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() {

@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 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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值