美文网首页
Java Lambda-1 入门

Java Lambda-1 入门

作者: 巴巴11 | 来源:发表于2020-03-16 12:38 被阅读0次

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

一段代码入门

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;
    }
}

相关文章

网友评论

      本文标题:Java Lambda-1 入门

      本文链接:https://www.haomeiwen.com/subject/dnhgehtx.html