将消费者转换为功能 [英] Converting Consumers to Functions

查看:89
本文介绍了将消费者转换为功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

功能界面的许多lambda采用

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?

推荐答案

有很多可能有用的方法可能是添加到功能消费者供应商接口。您举了一个很好的例子(将消费者转换为函数),但还有许多其他可能的转换或实用程序可以加上。例如,使用函数作为消费者(通过忽略返回值)或作为供应商(通过提供输入值)。或者通过提供任一值将 BiFunction 转换为函数。当然,所有这些都可以通过代码手动完成,或者通过实用程序功能提供,但是在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 实用程序的对比(作为一个例子)很感兴趣,以反转订单,按几个标准进行比较,处理null这些也很容易留给用户,但是由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.

这篇关于将消费者转换为功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆