Lambda & Stream 简明笔记

文章尝试回答以下问题:
1、什么是Lambda表达式
2、函数式接口
3、什么是Stream?

1、什么是Lambda表达式

一种写匿名类的新语法,From Java 8

    Runnable r = new Runnable() {
    public void run() { int i = 0;
          while (i++ < 10) {
    Sytem.out.println("just for fun"); }
    } };

------>

    Runnable r = () -> { int i = 0;
    while (i++ < 10) { Sytem.out.println("just for fun");
    }
    };

使用时,简化了匿名类的写法;
下面介绍另外一种替代写法Method References

Function<Person, Integer> f = person -> person.getAge() ;
Function<Person, Integer> f = Person::getAge ;

这种方法Ref 常用于Bean的取值

2、函数式接口

函数式接口:只有一个抽象方法的接口
注意,这里说的是抽象方法,default和静态方法都不受限制
为了防止编译错误,我们可以为想要定义为函数式接口的接口加上@FunctionalInterface注解。
下面介绍四种基本的functional interface

①、Consumer

@FunctionalInterface
public interface Consumer<T> {
    public void accept(T t);
}
public class Demo1 {
    public static void main(String[] args) {
        Consumer<String> printer = System.out::println;
        printer.accept("kkk");
        }
}
// kkk

②、Supplier

@FunctionalInterface
public interface Function<T, R> {
    public R apply(T t);
}
public class Demo1 {
    public static void main(String[] args) {
        Function<Person, Integer> ageMapper = p -> p.getAge();
        Integer apply = ageMapper.apply(new Person("Chris", "Paul", 24));
        System.out.println("apply = " + apply);
        //apply = 24
    }
}

③、Predicates

@FunctionalInterface
public interface Predicates<T> {
    public boolean test(T t);
}
public class Demo1 {
    public static void main(String[] args) {
        Predicates<Person> ageGT20 = p -> p.getAge() > 20;
        boolean test = ageGT20.test(new Person("tom", "tom", 18));
        System.out.println("test = " + test);
        //test = false
    }
}

4、Supplier

public class Demo1 {
    public static void main(String[] args) {
            Supplier<Person> personSupplier = () -> new Person("Chris", "Paul", 24);
            Person person = personSupplier.get();
            System.out.println("person = " + person);
            //person = Person{firstName=Chris, lastName=Paul, age=24}
    }
}

总结而言这四种基本类型的区别为:
Consumer:返回为空
Supplier:参数为空
Function:不受限制
Predicates:返回布尔类型

3、什么是Stream?

Stream:将数据从一个Source中推出

  • Stream不持有任何数据
  • Stream不修改数据
  • Stream 的Source可能是无穷的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值