Java 使用 Stream API 在每个对象上调用方法的“好”方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27534684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:32:24  来源:igfitidea点击:

"Good" method to call method on each object using Stream API

javalambdajava-8java-stream

提问by Jofkos

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?

方法引用是否有可能,或者是x -> x.method()唯一的方法在这里工作?

采纳答案by Eran

You don't need this. YourClassName::closewill call the closemethod on the object passed to the consumer :

你不需要this. YourClassName::close将调用close传递给消费者的对象的方法:

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

There are four kinds of method references (Source):

有四种方法引用(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.

在你的情况下,你需要第三种。

回答by Edwin Dalorzo

I suppose it should be:

我想应该是:

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

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

提供log.getHandlers()返回类型为 的对象数组Handler

回答by matsev

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

当然可以,但是您必须使用方法引用的正确语法,即传递close()方法所属的类:

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