0

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?

Rence
  • 2,900
  • 2
  • 23
  • 40

2 Answers2

5

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
CTroller
  • 166
  • 6
0

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()));
rohit kumbhar
  • 121
  • 1
  • 8