Rence
Rence

Reputation: 2950

SonarLint: Replace this lambda with a method reference

I have a collection that contains a list of errors. I wanted to group these by a key (UUID UserId). For this I have copied the code from this answer: https://stackoverflow.com/a/30202075/4045364

Collection<FilterError> filterErrors = new ArrayList<FilterError>();

// ... some filterErrors get added to the collection ...

return filterErrors.stream().collect(Collectors.groupingBy(w -> w.getUserId()));

Sonar Lint gives me the following error:

Replace this lambda with a method reference. ->

What I have tried:

Based on these question: SONAR: Replace this lambda with a method reference and Runable Interface : Replace this lambda with a method reference. (sonar.java.source not set. Assuming 8 or greater.)

filterErrors.stream().collect(Collectors.groupingBy(this::getUserId()));

Based on this question: Replace this lambda with method reference 'Objects::nonNull'

filterErrors.stream().collect(Collectors.groupingBy(UUID::getUserId()));

Both give the error:

The target type of this expression must be a functional interface

Is there a way I can resolve this SonarLint issue?

Upvotes: 0

Views: 1573

Answers (2)

rohit kumbhar
rohit kumbhar

Reputation: 121

In my case previously it was like this -

whitelist0.stream().filter(whitelistEntry -> !whitelistEntry.isEmpty()).map(s -> WhitelistEntry.of(s)).collect(Collectors.toList()));

As I need to pass a value to the function, so I did the following to replace the lambda with method reference -

whitelist0.stream().filter(whitelistEntry -> !whitelistEntry.isEmpty()).map(WhitelistEntry :: of).collect(Collectors.toList()));

Upvotes: 0

CTroller
CTroller

Reputation: 166

You need to use the class name of the object being targeted by the stream. Example:

List<String> list = ...;
list.stream().collect(Collectors.groupingBy(String::toUpperCase));

so in your case:

FilterError::getUserId

Upvotes: 5

Related Questions