如何在 java 8 中解决此 'Lambdas should be replaced with method references' 声纳问题?

How to fix this 'Lambdas should be replaced with method references' sonar issue in java 8?

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 lambda 函数,如下所示。

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

现在,我收到声纳问题,例如 Lambdas should be replaced with method references 到 '->' 这个符号。我该如何解决这个问题?

你的 lambda,

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

可以替换为

.map(NurseViewPrescriptionWrapper::new)

该语法是方法参考语法。在 NurseViewPrescriptionWrapper::new 的情况下是引用构造函数的特殊方法引用

如果你有一个合适的构造函数,你可以简单地将你的语句替换为:

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