java 8+中的lambda是流中唯一允许的单参数方法引用
在Java 8中的Stream
中,您只能使用带单个参数的方法引用(如果您不允许用方法调用包装方法引用),这是真的吗
我这样假设是因为在流中,您随时都在处理单个项目
因此:
Something::new
(必须引用单个参数构造函数)this::doSomething
(必须采用单个参数)Something::doSomething
(必须使用单个arg)
。。。在Stream
中使用时。这条规则总是正确的吗
你可以在下面搜索框中键入要查询的问题!
在Java 8中的Stream
中,您只能使用带单个参数的方法引用(如果您不允许用方法调用包装方法引用),这是真的吗
我这样假设是因为在流中,您随时都在处理单个项目
因此:
Something::new
(必须引用单个参数构造函数)this::doSomething
(必须采用单个参数)Something::doSomething
(必须使用单个arg)。。。在Stream
中使用时。这条规则总是正确的吗
# 1 楼答案
再加上answer from Eran,你可能会找到一个更容易理解的真实例子
让我们假设我们有一个方法,它添加了
Integer i
和intValue
的Long l
作为String s
表示返回。这看起来像:在
FunctionalInterface
的世界中,这可以表示为BiFunction
的匿名类:在lambda世界中,可以用以下形式表示:
也可以使用方法引用来表示,方法所在的类的对象为:
# 2 楼答案
不,不是。一些
Stream
方法采用函数接口,该接口具有一个具有多个参数的方法例如,
Stream
的sorted(Stream<T> Comparator<? super T> comparator)
方法采用Comparator
,其方法有两个参数下面是一个使用具有两个参数的方法的方法引用
String::compareTo
的示例:Stream
的Optional<T> max(Comparator<? super T> comparator)
方法是另一个类似的例子# 3 楼答案
有四种方法参考:
静态方法的方法引用,即
Class::staticMethod
>(args) -> Class.staticMethod(args)
对特定类型对象的实例方法的方法引用。i、 e
ObjectType::instanceMethod
>(obj, args) -> obj.instanceMethod(args)
对现有对象实例方法的方法引用,即
obj::instanceMethod
>(args) -> obj.instanceMethod(args)
对构造函数的方法引用,即
ClassName::new
>(args) -> new ClassName(args)
正如您在第二个示例中看到的,一个给定的方法可以接受两个参数,但仍然可以转换为方法引用,对于调用
sorted
、min
、max
等的情况也是如此。。一条小溪上面的例子要归功于Java 8 Method Reference: How to Use it