Search code examples
javasonarqube

Using Method Cast instead of Lambda on List with Objects


I am working on fixing some Sonar - Codesmells in my project at the moment. Sonar is pointing me at this method:

    protected List<Long> rolesIdsFromPortalSpecificAuthorizations(final List<PortalSpecificAuthorization> portalSpecificAuthorizations) {
             return portalSpecificAuthorizations.stream().map(portalSpecificAuthorization -> portalSpecificAuthorization.getId()).collect(Collectors.toList());
}

It says:

Replace this lambda with a method reference.

The PortalSpecificAuthorization is an object from my own coding. I was not able to find an easy-to-use solution for this case with Method casts.
What is the correct usage in this case?


Solution

  • Sonar wants a Method Reference instead of the lambda.

    Replace this part:

    portalSpecificAuthorization -> portalSpecificAuthorization.getId()
    

    with this

    PortalSpecificAuthorization::getId
    

    More about Method References: https://www.javatpoint.com/java-8-method-reference


    Full Code:

    protected List<Long> rolesIdsFromPortalSpecificAuthorizations(final List<PortalSpecificAuthorization> portalSpecificAuthorizations) {
        return portalSpecificAuthorizations.stream()
                  .map(PortalSpecificAuthorization::getId)
                  .collect(Collectors.toList());
    }