【问题标题】:How to fix this 'Lambdas should be replaced with method references' sonar issue in java 8?如何解决 java 8 中的“Lambdas 应该用方法引用替换”声纳问题?
【发布时间】:2019-01-08 06:14:48
【问题描述】:
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());
}

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

【问题讨论】:

  • 简单的方法是定义一个将NurseViewPrescriptionDTO作为参数并将其转换为NurseViewPrescriptionWrapper的方法。喜欢private NurseViewPrescriptionWrapper convert(NurseViewPrescriptionDTO d){return new NurseViewPrescriptionWrapper(d);} 然后在... map(YOURCALSS::convert) ...中使用

标签: java lambda java-8 method-reference


【解决方案1】:

你的 lambda,

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

可以替换为

.map(NurseViewPrescriptionWrapper::new)

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 2016-01-03
      • 2019-06-12
      • 1970-01-01
      • 2021-03-10
      • 2021-09-18
      相关资源
      最近更新 更多