Why doesn't java.util.function.Consumer have identity ()?

I just noticed that Consumerit has no method identity(), for example java.util.function.Function.

Yes, it would be just a hole into which the material could be poured, but at least it would be very clear that I didn’t just miss some kind of code in brackets.

Take this contrived example:

public void applyConsumerIfExists(String key, String param) {
    Map<String, Consumer<String>> consumers = new HashMap<>();
    consumers.put("a", MyClass::myConsumer);

    // I can create my own, but that no fun :(
    Consumer<String> identity = input -> {};
    consumers.getOrDefault(key, identity).accept(param);

    // DOESN'T WORK, since identity() doesn't exist on Consumer
    consumers.getOrDefault(key, Consumer.identity()).accept(param);
}

Question

Why not Consumerthe hava a method identity?

+4
source share
1 answer

Why Consumer<T>is there no identification method?

Consumer<T>always consumes an object of type Tand returns void.

.identity(), void void, void , , .

Function<T, R> , T R . Consumer<T> void, , .

+2

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


All Articles