简体   繁体   中英

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?

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

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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM