使用Stream API在每个对象上调用方法的“好”方法
是否可以在消费者中运行方法,如方法引用,但是在传递给使用者的对象上:
Arrays.stream(log.getHandlers()).forEach(h -> h.close());
会是这样的事情:
Arrays.stream(log.getHandlers()).forEach(this::close);
但那不行……
是否有可能使用方法引用,或者x -> x.method()
是在这里工作的唯一方法吗?
你不需要this
。 YourClassName::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);
- 谁实际实现了可序列化方法?
- eclipse中的Maven错误(pom.xml):无法转移org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4
- 原始分配了一个内存地址?
- 如何在web.xml中设置会话超时(以秒为单位)?
- 是否有一个类似于PropertyPlaceholderConfigurer的类用于接受XML的Spring?
- 为什么这在Java7中编译而在Java8中不编译?
- 使用java的multithreading概念控制运行Thread
- JSch中’shell’通道和’exec’通道之间有什么区别
- Sigar UnsatisfiedLinkError