java的几个函数式接口案例
基本都是使用lambda表达式重写方法
Supplier
import java.util.function.Supplier;
//生产数据的接口
public class SupplierDemo {
public static void main(String[] args) {
//lambda表达式重写接口中方法
String s = getString(() -> "chris");
System.out.println(s);
int i = getNumber(() -> 666);
System.out.println(i);
}
//生产数据
private static String getString(Supplier<String> supplier){
return supplier.get();
}
private static int getNumber(Supplier<Integer> supplier){
return supplier.get();
}
}
Consumer
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
// ConsumeString("chris", System.out::println);
//
// ConsumeString("Tom",System.out::println,s -> System.out.println(new StringBuilder(s).reverse().toString()));
String[] array = {"林青霞,30","张曼玉,33"};
for (String s : array) {
ConsumeString(s,s1 -> System.out.println(s.split(",")[0]),s1 -> System.out.println(s.split(",")[1]));
}
}
//消费数据
private static void ConsumeString(String s, Consumer<String> consumer){
consumer.accept(s);
}
private static void ConsumeString(String s, Consumer<String> consumer,Consumer<String> stringConsumer){
consumer.andThen(stringConsumer).accept(s);
}
}
Predicate
import java.util.function.Predicate;
//逻辑判断
public class PredicateDemo {
public static void main(String[] args) {
String[] array = {"林青霞,30","柳岩,34","张曼玉,35","貂蝉,31"};
for (String s : array) {
if (PredicatePeople(s,s1 -> s1.split(",")[0].length() > 2,s1 -> Integer.parseInt(s1.split(",")[1]) > 33)){
System.out.println(s);
}
}
}
private static boolean PredicatePeople(String s, Predicate<String> predicate, Predicate<String> stringPredicate){
return predicate.and(stringPredicate).test(s);
}
}
Function
import java.util.function.Function;
//数据转型
public class FunctionDemo {
public static void main(String[] args) {
String s = "林青霞,30";
TestFunction(s,s1 -> Integer.parseInt(s1.split(",")[1])+70);
}
private static void TestFunction(String s, Function<String,Integer> function){
int i = function.apply(s);
System.out.println(i);
}
}