Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Many lambdas for the Function interface take the form

t -> {
    // do something to t
    return t;
}

I do this so often that I have written a method for it like this.

static <T> Function<T, T> consumeThenReturn(Consumer<T> consumer) {
    return t -> {
        consumer.accept(t);
        return t;
    };
}

This enables me to do really nice things like this:

IntStream.rangeClosed('A', 'Z')
         .mapToObj(a -> (char) a)
         .collect(Collectors.collectingAndThen(Collectors.toList(), consumeThenReturn(Collections::shuffle)))
         .forEach(System.out::print); 

Is there another way to do conversions like this without relying on my own method? Is there anything in the new APIs I have missed that makes my method redundant?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
324 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are many potentially useful methods that could be added to the Function, Consumer and Supplier interfaces. You give a good example (converting a Consumer to a Function) but there are many other potential conversions or utilities that could be added. For example, using a Function as Consumer (by ignoring the return value) or as a Supplier (by providing an input value). Or converting a BiFunction to a Function by supplying either value. All of these can, of course, be done manually in code or provided via utility functions as you've shown but it would arguably be valuable to have standardised mechanisms in the API, as exist in many other languages.

It is speculation on my part, but I would guess this reflects the language designers' desire to leave the API as clean as possible. However I'm intrigued by the contrast (as an example) to the very rich set of Comparator utilities provided by the language to reverse orders, compare by several criteria, deal with null values etc. These also could easily have been left to the user but have been supplied by the API. I'd be interested to hear from one of the language designers why the approaches to these interfaces seems so inconsistent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...