函数型接口
源码分析
@FunctionalInterface
public interface Function {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
代码实现
/*
Function 函数型接口,有一个输入参数,有一个输出
只要是函数式接口就可以用lambda表达式简化
*/
public class Demo01 {
public static void main(String[] args) {
// 工具类: 输出输入的值
// Function function = new Function() {
// @Override
// public String apply(String str) {
// return str;
// }
// };
Function function = (str) -> {
return str;
};
System.out.println(function.apply("123"));
}
}
断定型接口
源码分析
@FunctionalInterface
public interface Predicate {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
代码实现
/*
断定型接口: 有一个输入参数,返回值只能是布尔值!
*/
public class Demo02 {
public static void main(String[] args) {
// 判断字符串是否为空
// Predicate predicate = new Predicate(){
// @Override
// public boolean test(String str) {
// return str.isEmpty();
// }
// };
Predicate predicate = (str) -> {
return str.isEmpty();
};
System.out.println(predicate.test(""));
}
}
消费型接口
源码分析
@FunctionalInterface
public interface Consumer {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
代码实现
/*
Consumer 消费型接口: 只有输入,没有返回值
*/
public class Demo03 {
public static void main(String[] args) {
// Consumer consumer = new Consumer() {
// @Override
// public void accept(String str) {
// System.out.println(str);
// }
// };
Consumer consumer = (str) -> {
System.out.println(str);
};
consumer.accept("asd");
}
}
供给型接口
源码分析
@FunctionalInterface
public interface Supplier {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
代码实现
/*
Supplier 供给型接口,没有参数,只有返回值
*/
public class Demo04 {
public static void main(String[] args) {
// Supplier supplier = new Supplier() {
// @Override
// public String get() {
// return "1024";
// }
// };
Supplier supplier = () -> {
return "1024";
};
System.out.println(supplier.get());
}
}