V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ningmengmao
V2EX  ›  Java

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

  •  
  •   ningmengmao · 2021-01-29 11:22:12 +08:00 · 1587 次点击
    这是一个创建于 1175 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 写法就不行了,这是为什么啊?

    4 条回复    2021-01-29 11:39:16 +08:00
    chendy
        1
    chendy  
       2021-01-29 11:25:35 +08:00
    () -> "str",这是个 Supplier (没参数又返回)
    然而要的是 Function (有参数有返回),所以应该是 app -> "str"
    ningmengmao
        2
    ningmengmao  
    OP
       2021-01-29 11:26:53 +08:00
    @chendy 但是那个 getString 方法的签名不也是() -> string 吗
    Oktfolio
        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"));
    ningmengmao
        4
    ningmengmao  
    OP
       2021-01-29 11:39:16 +08:00
    @Oktfolio 明白了,谢谢大佬
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5661 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:49 · PVG 09:49 · LAX 18:49 · JFK 21:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.