将消费者转换为函数
Function
接口的许多 lambdas 采用这种形式
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);
有没有其他方法可以在不依赖我自己的方法的情况下进行这样的转换?我错过的新 API 中是否有任何东西使我的方法变得多余?
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?
推荐答案
Function
、Consumer
和 中可以添加许多潜在有用的方法供应商
接口.您举了一个很好的例子(将 Consumer
转换为 Function
),但还有许多其他潜在的转换或实用程序可以添加.例如,使用 Function
作为 Consumer
(通过忽略返回值)或作为 Supplier
(通过提供输入值).或者通过提供任一值将 BiFunction
转换为 Function
.当然,所有这些都可以在代码中手动完成或通过实用程序函数提供,如您所展示的,但可以说在 API 中拥有标准化机制是有价值的,就像许多其他语言中存在的那样.
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.
这是我的猜测,但我想这反映了语言设计者希望让 API 尽可能干净的愿望.但是,我对与该语言提供的一组非常丰富的 Comparator
实用程序的对比(例如)很感兴趣,这些实用程序可以颠倒顺序、按多个标准进行比较、处理空值等.这些也可以很容易留给用户,但由 API 提供.我很想听听一位语言设计者为什么这些接口的方法看起来如此不一致.
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.
相关文章