为什么 Java 的 Function 接口可以接收 getMethod 这种方法签名的,用 lambda 就不行呢

2021-01-29 11:22:12 +08:00
 ningmengmao
public class App {

	public static void main(String[] args) {

		Map<String, String> collect = Stream.of(new App(), new App(), new App())
				.collect(Collectors.toMap(App::getString, (app) -> "aaa"));
                
//		Map<String, String> collect = Stream.of(new App(), new App(), new App())
//				.collect(Collectors.toMap(() -> "str", (app) -> "aaa"));

	}

	public String getString() {
		return "str";
	}
}

我用方法引用可以编译运行,但是用 lambda 写法就不行了,这是为什么啊?

1599 次点击
所在节点    Java
4 条回复
chendy
2021-01-29 11:25:35 +08:00
() -> "str",这是个 Supplier (没参数又返回)
然而要的是 Function (有参数有返回),所以应该是 app -> "str"
ningmengmao
2021-01-29 11:26:53 +08:00
@chendy 但是那个 getString 方法的签名不也是() -> string 吗
Oktfolio
2021-01-29 11:34:26 +08:00
上面那个是这样的啊,哪里一样了?

Map<String, String> collect = Stream.of(new App(), new App(), new App())
.collect(Collectors.toMap((it) -> {
return it.getString();
}, (app) -> "aaa"));
ningmengmao
2021-01-29 11:39:16 +08:00
@Oktfolio 明白了,谢谢大佬

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/749480

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX