java8中规范的四大函数式接口:
1、Consumer<T> :消费型接口 void accept(T t);
2、Supplier<T> :供给型接口 T get();
3、Function<T,R> :函数型接口 R apply(T t);
4、Predicate<T> :断言型接口 boolean test(T t);
事例一:
/**
* 消费形接口,有参数,无返回值
*/
public class ConsumerTest { public static void main(String[] args) { summer(10000, m -> System.out.println("世界那么大,我想去看看,可是钱包仅有:"+m+"元")); } public static void summer(double money, Consumer<Double> con) {
con.accept(money);
}
}
结果:
事例二:
/**
* 供给形接口,无参数有返回值
*/
public class SupplierTest { public static void main(String[] args) { List<Double> list = getRandomValue(5, () -> Math.random() * 100);
for (Double d : list) {
System.out.println(d);
}
} public static List<Double> getRandomValue(int num, java.util.function.Supplier<Double> sup) {
List<Double> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(sup.get());
}
return list;
}
}
结果:
结果:
事例三:
/**
* 函数形接口,有参数,有
*/
public class ConsumerTest { public static void main(String[] args) { String str = strHandler("一花一世界,一叶一菩提!", s -> s.substring(2,5));
System.out.println(str);
}
public static String strHandler(String str, Function<String, String> fun) {
return fun.apply(str);
}
}
结果:
事例四:
/**
* 断言形接口,有参数,返回boolean
*/
public class PredicateTest { public static void main(String[] args) { List<String> list = Arrays.asList("北京","南京","东京","长安","洛阳");
list = filterStr(list, s->s.contains("京"));
list.forEach(System.out::println);
} public static List<String> filterStr(List<String> list, Predicate<String> predicate) {
List<String> stringList = new ArrayList<>();
for (String str : list) {
if (predicate.test(str))
stringList.add(str);
}
return stringList;
}
}
结果: