有没有办法在不编写代码或添加额外库的情况下在链中使用消费者? 现在就像:
Consumer s = str -> System.out.println(str);
s.accept("abc");
s.accept("fgh");
s.accept("xyz");
有没有办法把它变成像
这样的东西Consumer s = str -> System.out.println("str");
s.accept("abc").accept("fgh").accept("xyz")
答案 0 :(得分:3)
由于accept()
会返回void
,因此您所要求的内容不可能“开箱即用”。
但是,你可以创建一些包装器来做你想要的。例如:
class ChainedConsumer<T> {
private final Consumer<T> consumer;
public ChainedConsumer(final Consumer<T> consumer) {
this.consumer = consumer;
}
public ChainedConsumer<T> accept(final T s) {
this.consumer.accept(s);
return this;
}
}
答案 1 :(得分:1)
如果您的环境允许制作Consumer
的包装,则可以创建自己的accept
方法,将签名从void
更改为Consumer
并返回{{ 1}}总是在构建器模式中。
答案 2 :(得分:1)
正如其他人提到的那样,Consumer
会返回void
,因此您无法将它们链接起来。但一切都归结为你想要实现的事情有多复杂。例如,您的特定示例可能是以这样的方式编写的:
Stream.of("abc", "fgh", "xyz").forEach(System.out::println);
字符串可以替换为任何对象,Consumer
可以是任何复杂的。但是,如果您不需要在一个链中的每个价值上执行消费者,那么这种方法就不适合您。