“Good” method to call method on each object using Stream API

假装没事ソ 提交于 2020-01-01 04:08:10

问题


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());

would be a thing like:

Arrays.stream(log.getHandlers()).forEach(this::close);

but that's not working...

Is there a possibility with method references, or is x -> x.method() the only way working here?


回答1:


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);

There are four kinds of method references (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.




回答2:


I suppose it should be:

Arrays.stream(log.getHandlers()).forEach(Handler::close);

Provided the log.getHandlers() returns an array of objects of type Handler.




回答3:


Sure, but you must use the correct syntax of method reference, i.e. pass the class to which the close() method belong:

Arrays.stream(log.getHandlers()).forEach(Handler::close);


来源:https://stackoverflow.com/questions/27534684/good-method-to-call-method-on-each-object-using-stream-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!