Compiled predicate in Java 8

In Guava, we can do things like

Predicate<String> isEmpty = Predicates.compose(String::length, Integer.valueOf(0)::equals); // contrived, I know

Is it possible to do something like this in Java 8? for instance

Predicate<Integer> isZero = Integer.valueOf(0)::equals;
Predicate<String> isEmpty = isZero.compose(String::length);

or a library function that is reachable in the same way?

Please note that I am not asking how to do this myself ( s -> isZero.test(s.length)works fine) or why it doesn't work on line (Lambda types are output and all that)

+4
source share
1 answer

You can easily write a method composeand use it in several places:

import java.util.function.*;

public class Test {
    public static void main(String[] args) {
        Integer zero = 0;
        Predicate<Integer> isZero = zero::equals;
        Predicate<String> isEmpty = compose(String::length, isZero);

        System.out.println(isEmpty.test("")); // true
        System.out.println(isEmpty.test("x")); // false
    }

    // Composition of a function with a predicate
    public static <T, S> Predicate<T> compose(Function<T, S> first, Predicate<S> second) {
        return input -> second.test(first.apply(input));
    }
}

(I removed the links to Integer.ZEROas this does not exist ...)

+3
source

Source: https://habr.com/ru/post/1662940/


All Articles