新时代的程序员:lambda表达式、链式编程、函数式接口、Stream流式计算
函数式接口就是只有一个方法的接口, 它有有个专门的注解, 我们平时使用的Runable 接口就是一个函数式的接口。函数式的接口可以使用lambda 表达式来简化编程。
@FunctionalInterface
public interface Runnable {
void run();
}
测试 Function
@FunctionalInterface
public interface Function<T, R> {
R apply(T var1);
}
// 传入 T R 返回 R
code
public class function {
public static void main(String[] args) {
Function<String, String> function = (test) -> {
return test + "cyt ";
};
/**
* 把 compose 计算的结果和apply 中的参数一起在进行计算。
*/
String apply = function2.compose(function).apply("test ");
String test = function2.apply("test");
/**
* 先计算 apply 中的结果,然后把结果放到 andThen 中计算。
*/
String ff = function2.andThen((f) -> {
return f + "dev";
}).apply("ff");
System.out.println(ff);
}
}
predicate 断定型接口:参数只有一个, 并且只有一个返回值, 只能是布尔值。
@FunctionalInterface
public interface Predicate<T> {
boolean test(T var1);
}
code
public class predicate {
public static void main(String[] args) {
/**
* 添加一个是否 包含 A 的断言
*/
Predicate<String> predicate = (str) -> {
return str.contains("A");
};
/**
* 添加多个条件 && 关系
*/
boolean b = predicate.and((ans) -> {
return ans.contains("ans");
}).test("Aans");
System.out.println(b);
/**
* 添加多个条件 || 关系
*/
predicate.or((test) -> {
return test.length() > 2;
});
/**
*简化写法
*/
Predicate<Integer> pre = (a) -> a > 2 || a % 2 == 0;
}
}
Supplier 供给型接口 没有参数、只有返回值
code
public class SupplierTest {
public static void main(String[] args) {
Supplier<String> supplier = () -> {
return "1024";
};
System.out.println(supplier.get());
}
}
Consume 消费型接口
public interface Consumer<T> {
void accept(T var1);
}
// 只有输入, 没有返回值
code
public class Consume {
public static void main(String[] args) {
Consumer<String> c = (str) -> {
System.out.println(str);
};
c.accept("asd");
}
}