The most crucial distinguish between functional interface invoking and traditional method invoking is that transforming behavious or params it is.However,Transforming behavior is more encapsulated and abstract.The logic methods does not implement predicatbly.We can get any result while invoking method by transforming behavious.
Example of some crucial functional interface:
1. public interface Function<T, R>
the mainly method:
/** * Applies this function to the given argument. * * @param t the function argument * @return the function result */ R apply(T t);
ex:
list.stream().map(item -> item.toUpperCase()).forEach(item -> System.out.println(item)); equals: list.stream().map(String::toUpperCase).forEach(System.out::println); In String class (invoke object is param): public String toUpperCase() { return toUpperCase(Locale.getDefault()); } In PrintStream(System.out) class: public void println(String x) { synchronized (this) { print(x); newLine(); } } And public interface BiFunction<T, U, R>
/** * Applies this function to the given arguments. * * @param t the first function argument * @param u the second function argument * @return the function result */ R apply(T t, U u);
Some functions that have the prefix of Bi is possessing two params and a result.
2. public interface Consumer<T>
the mainly method:
/** * Performs this operation on the given argument. * * @param t the input argument */ void accept(T t);
3. public interface Supplier<T>
the mainly method:
/** * Gets a result. * * @return a result */ T get();
And public interface BinaryOperator<T> extends BiFunction<T,T,T>
/** * Returns a {@link BinaryOperator} which returns the lesser of two elements * according to the specified {@code Comparator}. * * @param <T> the type of the input arguments of the comparator * @param comparator a {@code Comparator} for comparing the two values * @return a {@code BinaryOperator} which returns the lesser of its operands, * according to the supplied {@code Comparator} * @throws NullPointerException if the argument is null */ public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator); return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; }
4. public interface Predicate<T>
/** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(T t);
ex:
stream().filter(item -> item>2)...
时间: 2024-11-18 04:32:16