ningmengmao
V2EX  ›  Java

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

  •  
  •   ningmengmao · Jan 29, 2021 · 2426 views
    This topic created in 1935 days ago, the information mentioned may be changed or developed.
    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 replies    2021-01-29 11:39:16 +08:00
    chendy
        1
    chendy  
       Jan 29, 2021
    () -> "str",这是个 Supplier (没参数又返回)
    然而要的是 Function (有参数有返回),所以应该是 app -> "str"
    ningmengmao
        2
    ningmengmao  
    OP
       Jan 29, 2021
    @chendy 但是那个 getString 方法的签名不也是() -> string 吗
    Oktfolio
        3
    Oktfolio  
       Jan 29, 2021
    上面那个是这样的啊,哪里一样了?

    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
       Jan 29, 2021
    @Oktfolio 明白了,谢谢大佬
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2972 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 12:48 · PVG 20:48 · LAX 05:48 · JFK 08:48
    ♥ Do have faith in what you're doing.