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 写法就不行了,这是为什么啊?
1
chendy 2021-01-29 11:25:35 +08:00
() -> "str",这是个 Supplier (没参数又返回)
然而要的是 Function (有参数有返回),所以应该是 app -> "str" |
2
ningmengmao OP @chendy 但是那个 getString 方法的签名不也是() -> string 吗
|
3
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")); |
4
ningmengmao OP @Oktfolio 明白了,谢谢大佬
|