-
Predicate
java.util.function.Predicate<T>
接口定義了一個名叫test
的抽象方法仆潮,它接受泛型T對象,并返回一個boolean
遣臼。@FunctionalInterface public interface Predicate<T>{ boolean test(T t); } public static <T> List<T> filter(List<T> list, Predicate<T> p) { List<T> results = new ArrayList<>(); for(T s: list){ if(p.test(s)){ results.add(s); } } return results; } Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty(); List<String> nonEmpty = filter(listOfStrings, nonEmptyStringPredicate);
-
Consumer
java.util.function.Consumer<T>
定義了一個名叫accept
的抽象方法性置,它接受泛型T的對象,沒有返回(void
)揍堰。你如果需要訪問類型T的對象鹏浅,并對其執(zhí)行某些操作,就可以使用這個接口屏歹。例如隐砸,可以創(chuàng)建一個ForEach方法@FunctionalInterface public interface Consumer<T>{ void accept(T t); } public static <T> void forEach(List<T> list, Consumer<T> c){ for(T i: list){ c.accept(i); } } forEach( Arrays.asList(1,2,3,4,5), (Integer i) -> System.out.println(i) );
-
Function
java.util.function.Function<T, R>
接口定義了一個叫作apply
的方法,它接受一個泛型T的對象蝙眶,并返回一個泛型R的對象季希。如果你需要定義一個Lambda褪那,將輸入對象的信息映射到輸出,就可以使用這個接口@FunctionalInterface public interface Function<T, R>{ R apply(T t); } public static <T, R> List<R> map(List<T> list, Function<T, R> f) { List<R> result = new ArrayList<>(); for(T s: list){ result.add(f.apply(s)); } return result; } // [7, 2, 6] List<Integer> l = map( Arrays.asList("lambdas","in","action"), (String s) -> s.length() );
image.png
image.png