如何解决此“ Lambdas应替换为方法引用” Java 8中的声纳问题?

时间:2019-01-08 06:14:48

标签: java lambda java-8 method-reference

 public static Set<NurseViewPrescriptionWrapper> create(final Set<NurseViewPrescriptionDTO> nurseViewPrescriptionDTOs)   {
    return nurseViewPrescriptionDTOs.stream().map(new Function<NurseViewPrescriptionDTO, NurseViewPrescriptionWrapper>()
    {
      @Override public NurseViewPrescriptionWrapper apply(NurseViewPrescriptionDTO input)
      {
        return new NurseViewPrescriptionWrapper(input);
      }
    })
      .collect(Collectors.toSet());   }

我将上述代码转换为Java 8 lamda函数,如下所示。

  public static Set<NurseViewPrescriptionWrapper> create(final Set<NurseViewPrescriptionDTO> nurseViewPrescriptionDTOs)
  {
    return nurseViewPrescriptionDTOs.stream().map(input -> new NurseViewPrescriptionWrapper(input))
      .collect(Collectors.toSet());
  }

现在,我正在接收声纳问题,例如“应将Lambda替换为方法引用”,以该符号“->”。如何解决此问题?

2 个答案:

答案 0 :(得分:4)

您的lambda,

.map(input -> new NurseViewPrescriptionWrapper(input))

可以替换为

.map(NurseViewPrescriptionWrapper::new)

该语法是方法参考语法。对于NurseViewPrescriptionWrapper::new是一个特殊的方法引用,它引用一个构造函数

答案 1 :(得分:3)

鉴于您有一个适当的构造函数,只需将语句替换为:

public static Set<NurseViewPrescriptionWrapper> create(final Set<NurseViewPrescriptionDTO> nurseViewPrescriptionDTOs) {
    return nurseViewPrescriptionDTOs.stream()
                            .map(NurseViewPrescriptionWrapper::new)
                            .collect(Collectors.toSet());
}
相关问题