使用Lambda与方法引用改进List排序写法

使用Lambda与方法引用对List排序

下面通过参考代码演示实现“原始”写法如何演进到函数式编程的过程。

定义一下相关类

/**
* 定义苹果类
*/
public class Apple {
	private int weight = 0;
	private String color = "";
	public Apple(Integer weight, String color){
            this.weight = weight;
            this.color = color;
    }
	//省略Getter Setter
}

// 初始化List数据
 List<Apple> inventory = new ArrayList<>();
 inventory.addAll(Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red")));

1. 内部类传递实现

// 定义比较器
class AppleComparator implements Comparator<Apple> {
        public int compare(Apple a1, Apple a2){
            return a1.getWeight().compareTo(a2.getWeight());
        }
    }
 // 通过比较器过滤
inventory.sort(new AppleComparator());

2. 匿名内部类简化代码

 inventory.sort(new Comparator<Apple>() {
    public int compare(Apple a1, Apple a2){
        return a1.getWeight().compareTo(a2.getWeight()); 
 }});

3. Lambda引入

// a. 替换匿名内部类
inventory.sort((Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight()));
// b. Lambda支持上下文类型推算,可以省略参数类型
inventory.sort((a1, a2) -> a1.getWeight().compareTo(a2.getWeight()));

4. 使用Comparator提供的comparing方法简化

Comparator具有一个叫作comparing的静态辅助方法,它可以接受一个Function来提取Comparable键值,并生成一个Comparator对象

inventory.sort(Comparator.comparing((a) -> a.getWeight()));

5. 方法引用

// 静态引入方法
import static java.util.Comparator.comparing;
// 方法引用替代Lambda表达式
inventory.sort(comparing(Apple::getWeight));

参考

  • Java8 In Action . Part 3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值