文章尝试回答以下问题:
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可能是无穷的