【问题标题】:Java8 .getMethod() vs ::getMethodJava8 .getMethod() 与 ::getMethod
【发布时间】:2018-11-30 15:29:16
【问题描述】:

我是 Java8 的新手,我创建的这段代码运行良好

 userService.getClient().findUsersByMarkets(marketIds)
                .stream()
                .filter(us -> !alreadyNotifiedUserIds.contains(us.getId()))
                .forEach(usersToBeNotified::add);

但根据我的理解,这段代码也应该可以正常工作,但事实并非如此,我想知道为什么

     userService.getClient().findUsersByMarkets(marketIds)
        .stream()
        .filter(us -> !alreadyNotifiedUserIds.contains(User::getId))
        .forEach(usersToBeNotified::add);

【问题讨论】:

  • 您在调用实例和类的方法之间切换。
  • 什么理解? us.getId()User::getId 是完全不同的结构。
  • 附带说明,.forEach(usersToBeNotified::add) 最好由.collect(Collectors.toList()) 实现
  • 如果你使用filter(us -> us.isFoo()) 就对了,它等同于filter(User::isFoo)

标签: java java-8 functional-programming java-stream


【解决方案1】:

User::getId 是对函数的引用,因此它不等同于 contains(us.getId())

请参阅 --> https://www.codementor.io/eh3rrera/using-java-8-method-reference-du10866vx 以熟悉方法引用。

【讨论】:

  • User::getId 等同于 (User x) -> x.getId()
猜你喜欢
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
相关资源
最近更新 更多