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

是否可以在消费者中运行方法,如方法引用,但是在传递给使用者的对象上:

Arrays.stream(log.getHandlers()).forEach(h -> h.close()); 

会是这样的事情:

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

但那不行……

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

你不需要thisYourClassName::close将调用传递给使用者的对象的close方法:

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

有四种方法参考( 来源 ):

 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 

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

我想它应该是:

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

如果log.getHandlers()返回Handler类型的对象数组。

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

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