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?
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