"良好的"使用Stream API在每个对象上调用方法的方法 [英] "Good" method to call method on each object using Stream API
本文介绍了"良好的"使用Stream API在每个对象上调用方法的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在消费者中运行方法,如方法引用,但是传递给消费者的对象:
Is it possible to run a method, in a consumer, like a method reference, but on the object passed to the consumer:
Arrays.stream(log.getHandlers()).forEach(h -> h.close());
会是这样的:
Arrays.stream(log.getHandlers()).forEach(this::close);
但这不起作用......
but that's not working...
是否有可能使用方法引用,或 x - > x.method()
在这里工作的唯一方法是什么?
Is there a possibility with method references, or is x -> x.method()
the only way working here?
推荐答案
你不需要此
。 YourClassName :: close
将在传递给消费者的对象上调用 close
方法:
You don't need this
. YourClassName::close
will call the close
method on the object passed to the consumer :
Arrays.stream(log.getHandlers()).forEach(YourClassName::close);
有四种方法引用( Source ):
Kind Example
---- -------
Reference to a static method ContainingClass::staticMethodName
Reference to an instance method of a particular object containingObject::instanceMethodName
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName
Reference to a constructor ClassName::new
在你的情况下,你需要第三种。
In your case, you need the third kind.
这篇关于"良好的"使用Stream API在每个对象上调用方法的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文