Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 749
uma Avatar asked Mar 05 '23 18:03

uma


1 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

like image 93
sweet suman Avatar answered Apr 07 '23 05:04

sweet suman