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);
事例一:
1 /** 2 * 消费形接口,有参数,无返回值 3 */ 4 public class ConsumerTest { 5 6 public static void main(String[] args) { 7 8 summer(10000, m -> System.out.println("世界那么大,我想去看看,可是钱包仅有:"+m+"元")); 9 10 } 11 12 public static void summer(double money, Consumer<Double> con) { 13 con.accept(money); 14 } 15 }
结果:
事例二:
1 /** 2 * 供给形接口,无参数有返回值 3 */ 4 public class SupplierTest { 5 6 public static void main(String[] args) { 7 8 List<Double> list = getRandomValue(5, () -> Math.random() * 100); 9 for (Double d : list) { 10 System.out.println(d); 11 } 12 } 13 14 public static List<Double> getRandomValue(int num, java.util.function.Supplier<Double> sup) { 15 List<Double> list = new ArrayList<>(); 16 for (int i = 0; i < num; i++) { 17 list.add(sup.get()); 18 } 19 return list; 20 } 21 }
结果:
结果:
事例三:
/** * 函数形接口,有参数,有 */ 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); } }
结果:
事例四:
1 /** 2 * 断言形接口,有参数,返回boolean 3 */ 4 public class PredicateTest { 5 6 public static void main(String[] args) { 7 8 List<String> list = Arrays.asList("北京","南京","东京","长安","洛阳"); 9 list = filterStr(list, s->s.contains("京")); 10 list.forEach(System.out::println); 11 } 12 13 public static List<String> filterStr(List<String> list, Predicate<String> predicate) { 14 List<String> stringList = new ArrayList<>(); 15 for (String str : list) { 16 if (predicate.test(str)) 17 stringList.add(str); 18 } 19 return stringList; 20 } 21 }
结果: