[英]SonarLint: Replace this lambda with a method reference
我有一個包含錯誤列表的集合。 我想通過一個鍵(UUID UserId)對這些進行分組。 為此,我從這個答案中復制了代碼: 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 給了我以下錯誤:
將此 lambda 替換為方法引用。
->
我嘗試過的:
基於這些問題: SONAR: Replace this lambda with a method reference and Runable Interface : Replace this lambda with a method reference。 (sonar.java.source 未設置。假設為 8 或更大。)
filterErrors.stream().collect(Collectors.groupingBy(this::getUserId()));
基於這個問題: 用方法引用 'Objects::nonNull' 替換這個 lambda
filterErrors.stream().collect(Collectors.groupingBy(UUID::getUserId()));
兩者都給出錯誤:
此表達式的目標類型必須是函數式接口
有沒有辦法解決這個 SonarLint 問題?
您需要使用流所針對的對象的類名。 例子:
List<String> list = ...;
list.stream().collect(Collectors.groupingBy(String::toUpperCase));
所以在你的情況下:
FilterError::getUserId
在我以前的情況下是這樣的 -
whitelist0.stream().filter(whitelistEntry -> !whitelistEntry.isEmpty()).map(s -> WhitelistEntry.of(s)).collect(Collectors.toList()));
由於我需要向函數傳遞一個值,因此我執行了以下操作以將 lambda 替換為方法引用 -
whitelist0.stream().filter(whitelistEntry -> !whitelistEntry.isEmpty()).map(WhitelistEntry :: of).collect(Collectors.toList()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.