Combining functions and consumers with a two-column designation

I often use double column notation for short.

I am writing the following method, which takes a short list of entities, validates them and stores them in a database.

@Override@Transactional
public void bulkValidate(Collection<Entity> transactions)
{
    Consumer<Entity> validator = entityValidator::validate;
    validator = validator.andThen(getDao()::update);
    if (transactions != null)
        transactions.forEach(validator);

}

I would like to know if there is a shorthand syntax not to instantiate a variable validator

The following syntax is invalid ("The target type of this expression must be a functional interface")

transactions.forEach((entityValidator::validate).andThen(getDao()::update));
+4
source share
1 answer

You can do this, but you will need to explicitly specify ...

 transactions.forEach(((Consumer<Entity>)(entityValidator::validate))
                             .andThen(getDao()::update));

The fact is that a reference to a method like this entityValidator::validateone is not of type, it is a poly expression, and it depends on the context.

:

@SafeVarargs
private static <T> Consumer<T> combine(Consumer<T>... consumers) {
    return Arrays.stream(consumers).reduce(s -> {}, Consumer::andThen);
}

:

transactions.forEach(combine(entityValidator::validate, getDao()::update))
+4

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


All Articles