Java Lambda-1 入门

2020-03-16  本文已影响0人  巴巴11

把方法当做一等公民
行为参数化

一段代码入门

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {
        List<Apple> lists = Arrays.asList(new Apple[]{
           new Apple(10),  new Apple(20), new Apple(30)
        });

        // 排序 传统写法
        /*Collections.sort(lists, new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return o1.getWeight().compareTo(o2.getWeight());
            }
        });*/
        // 更简洁的lambda写法
        lists.sort(Comparator.comparing(Apple::getWeight));

        lists.stream().forEach(l -> System.out.println(l.getWeight()));
    }
}
public class Apple {
    private int weight;

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public Apple(int weight) {
        this.weight = weight;
    }
}
上一篇下一篇

猜你喜欢

热点阅读