Lambda 函数式编程
lambda表达式是一段可以传递的代码,它的核心思想是将面向对象中的传递数据变成传递行为。
在java8之前我们如果需要使用Runnable新建一个线程的时候我们需要进行这样的操作
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("do something.");
}
}
使用lambda我们可以节省很多定义的操作.一行代码搞定,至少这样看起来是很爽的.
Runnable r = () -> System.out.println("do something.");
lambda表达式的基本规则
expression = (variable) -> action
其中variable为变量非必选字段
我们可以自己写个函数式接口
public class FunctionTest {
@FunctionalInterface
interface Predicate<T> {
boolean test(T t);
}
public static boolean doPredicate(int age, Predicate<Integer> predicate) {
return predicate.test(age);
}
public static void main(String[] args) {
boolean isAdult = doPredicate(20, x -> x >= 18);
System.out.println(isAdult);
}
}
这是FunctionalInterface注释的一部分
An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.
一种信息性注释类型,用于指示接口类型声明是由Java语言规范定义的功能接口
lambda内置函数式接口:
- Consumer 消费性接口 只接收数据,并没有返回值
- Supplier 供给型接口 没有参数,但是可以返回数据
- Function 函数型接口 既能输入数据,又能返回结果的方法
- Predicate 断言型接口 根据条件返回boolean
public class StreamDemo {
public static void main(String[] args) {
// 供给型接口
List<Double> list = supply(10,() -> Math.random()*100);
// 消费性接口
list.forEach(System.out::println);
// 断言型接口
List<Double> list1 = list.stream().filter(x -> x%2 == 0).collect(Collectors.toList());
list1.forEach(System.out::println);
// 函数型接口
List<Double> list2 = list.stream().map(x -> x*2).collect(Collectors.toList());
}
public static List<Double> supply(Integer num, Supplier<Double> supplier){
List<Double> resultList = new ArrayList<>();
for(int x=0;x<num;x++) {
resultList.add(supplier.get());
}
return resultList ;
}
}