0% found this document useful (0 votes)
8 views12 pages

P2 04 Java8 3 Functions Ua

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views12 pages

P2 04 Java8 3 Functions Ua

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Java 8

java.util.function
java.util.function
• Пакет…
• … в якому …
• … 43 функциональних інтерфейса
BiConsumer<T,U> BiFunction<T,U,R> BinaryOperator<T> BiPredicate<T,U>
BooleanSupplier Consumer<T> DoubleBinaryOperator DoubleConsumer
DoubleFunction<R> DoublePredicate DoubleSupplier DoubleToIntFunction
DoubleToLongFunction DoubleUnaryOperator Function<T,R>
IntBinaryOperator IntConsumer IntFunction<R> IntPredicate IntSupplier
IntToDoubleFunction IntToLongFunction IntUnaryOperator
LongBinaryOperator LongConsumer LongFunction<R> LongPredicate
LongSupplier LongToDoubleFunction LongToIntFunction LongUnaryOperator
ObjDoubleConsumer<T> ObjIntConsumer<T> ObjLongConsumer<T>
Predicate<T> Supplier<T> ToDoubleBiFunction<T,U> ToDoubleFunction<T>
ToIntBiFunction<T,U> ToIntFunction<T> ToLongBiFunction<T,U>
ToLongFunction<T> UnaryOperator<T>
java.util.function - why?
• Прежде чем делать открытие — загляни в справочник.
К. Прутков-инженер. «Советы начинающему гению»

• Перед тим, як вигадувати свій функціональний інтерфейс,


подивись у в java.util.function.*
Я :)
java.util.function
xxx: <T> int long double

Function<T,R> IntFunction<R> LongFunction<R> DoubleFunction<R>


Функції
(ххх) ==> <R>
BiFunction<T,U,R> ToIntBiFunction<T,U> ToLongBiFunction<T,U> ToDoubleBiFunction<T,U>

ToIntFunction<T> ToLongFunction<T> ToDoubleFunction<T>


Функції
LongToIntFunction IntToLongFunction IntToDoubleFunction
(ууу) ==> (ххх)
DoubleToIntFunction DoubleToLongFunction LongToDoubleFunction
Предикати Predicate<T>
IntPredicate LongPredicate DoublePredicate
(xxx) ==> boolean BiPredicate<T,U>
Унарні
оператори UnaryOperator<T> IntUnaryOperator LongUnaryOperator DoubleUnaryOperator
(xxx) ==> (xxx)
Бінарні
оператори BinaryOperator<T> IntBinaryOperator LongBinaryOperator DoubleBinaryOperator
(xxx, xxx) ==> (xxx)

Supplier<T> IntSupplier LongSupplier DoubleSupplier


Постачальники
void ==> (xxx)
BooleanSupplier

IntConsumer LongConsumer DoubleConsumer


Споживачі Consumer<T>
(xxx) ==> void BiConsumer<T,U>
ObjIntConsumer<T> ObjLongConsumer<T> ObjDoubleConsumer<T>
Приклад 1 - інтегратор (1/3)
import java.util.function.DoubleUnaryOperator;

interface Integrator {
double calculate(DoubleUnaryOperator fn, double from, double to);
}
Приклад 1 - інтегратор (2/3)
public class SquareIntegrator implements Integrator {
double step;
public SquareIntegrator(double step) {
this.step = step;
}

@Override
public double calculate(DoubleUnaryOperator fn, double from, double to) {
double result = 0;
double x = from;
double delta = (to > from) ? step : -step;
int n = (int)((to-from)/delta);
for (int i=0; i < n; i++, x += delta) {
result += fn.applyAsDouble(x) * delta;
}
return result;
}
Приклад 1 - інтегратор (3/3)
public static void main(String[] args) {
Integrator integrator = new SquareIntegrator(0.0001);

// Java 7 style
DoubleUnaryOperator duo = new DoubleUnaryOperator() {
@Override
public double applyAsDouble(double operand) {
return Math.sin(operand);
}
};
System.out.println(integrator.calculate(duo, 0, Math.PI / 2));

// Java 8 lambda style


System.out.println(integrator.calculate(x -> Math.sin(x), 0, Math.PI / 2));

}
java.util.function - продовження
• Деякі інтерфейси java.util.function крім
єдиного абстрактного метода також мають
static або default методи для додаткової
функціональності
Interface Function<T,R>
default <V> Function<T,V> andThen(Function<? super R,? extends V> after)
Returns a composed function that first applies this
T ==> R ==> V function to its input, and then applies the after function to
the result.

R apply(T t)
T ==> R Applies this function to the given argument.

default <V> Function<V,R> compose(Function<? super V,? extends T> before)


Returns a composed function that first applies the before
V ==> T ==> R function to its input, and then applies this function to the
result.

static <T> Function<T,T> identity()


Returns a function that always returns its input argument.
compose / andThen

Function<Integer, Integer> x2 = x -> x * 2;


Function<Integer, Integer> sqr = x -> x * x;

System.out.println( x2.andThen(sqr).apply(3) ); // (3 * 2) ^ 2 = 36
System.out.println( x2.compose(sqr).apply(3) ); // (3 ^ 2) * 2 = 18

System.out.println( sqr.andThen(x2).andThen(x2).apply(3) ); // (3^2)*2*2 = 36


System.out.println( sqr.compose(x2).compose(x2).apply(3) ); // (3*2*2)^2 = 144
Interface Predicate<T>
default Predicate<T> and(Predicate<? super T> other)
Returns a composed predicate that represents a short-circuiting
logical AND of this predicate and another.

static <T> Predicate<T> isEqual(Object targetRef)


Returns a predicate that tests if two arguments are equal
according to Objects.equals(Object, Object).

default Predicate<T> negate()


Returns a predicate that represents the logical negation of this
predicate.
default Predicate<T> or(Predicate<? super T> other)
Returns a composed predicate that represents a short-circuiting
logical OR of this predicate and another.

boolean test(T t)
Evaluates this predicate on the given argument.
and / or

IntPredicate csb = x -> x != 0; // C style boolean


System.out.println(csb.test(0)); // false
System.out.println(csb.test(1)); // true
System.out.println(csb.test(2)); // true
System.out.println("------------------------------");

IntPredicate t = x -> true; //always true


IntPredicate f = x -> false; //always false
System.out.println(t.or(t).and(f).test(1)); // false: no precedence!
System.out.println(true || true && false); // true: ‘and ‘ > ‘or’

You might also like