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

Viewed 1014
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());
}

I convert above code to java 8 lamda function as below.

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

Now, I am receiving sonar issue, like Lambdas should be replaced with method references , to '->' this symbol. How i can fix this issue ?

2 Answers

Your lambda,

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

can be replaced by

.map(NurseViewPrescriptionWrapper::new)

That syntax is a method reference syntax. In the case of NurseViewPrescriptionWrapper::new is a special method reference that refers to a constructor

Given you have an appropriate constructor, you could simply replace your statement as:

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