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 }
結果: