Suggestion to replace lambda with method reference causes invalid code (java:S1612)

Rule: Lambdas should be replaced with method references (java:S1612)

Applying suggestion to replace lambda on Integer conversion to String with method reference causes invalid code.

Original code:

Collection<Integer> idList;
// here we initialize collection
System.out.println(
    idList
        .stream()
        .map(i -> i.toString())
        .collect(Collectors.joining(", "))
);

Suggestion:

Replace this lambda with method reference ‘Integer::toString’.

Code after suggestion:

System.out.println(
    idList
        .stream()
        .map(Integer::toString)
        .collect(Collectors.joining(", "))
);

Error after code modified:

Ambiguous method reference: both toString() and toString(int) from the type Integer are eligible


P.S. System.out.println() is here just for example, I do not use it in code for real :slight_smile:


Before applying suggestion:

Sonar-1

After suggestion applied:

Thank you for the detailed and precise reporting @H.Lo !

I have created a ticket for the issue: [SONARJAVA-4329] - Jira

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.