Originally I had a class with a lambda function in a java class.
final Map<String, UserBean> users = persons.entrySet().stream()
.filter(entry -> !entry.getValue().getIsActive().booleanValue())
.collect(Collectors.toMap(
entry -> entry.getKey()
, entry -> entry.getValue()));
But sonar gave me a suggestion: Lambdas should be replaced with method references
So I started to output to external methods. I started by adding to the same class where the lambda was, a function that returned the key. And update the lambda as follows:
final Map<String, UserBean> users = persons.entrySet().stream()
.filter(entry -> !entry.getValue().getIsActive().booleanValue())
.collect(Collectors.toMap(
this::<String>getEntryKey
, entry -> entry.getValue()));
This worked perfectly for me and the sonar suggestion was only marked on the arrow that was on the bottom line of the statement that I modified. The issue is that I realized that this warning was repeated in many places in the code. So I started to make a utility class so as not to repeat code.
The utility class I have has two methods to get the keys and values of a map:
public class LambdaUtils {
private static final LambdaUtils INSTANCE = new LambdaUtils();
public static LambdaUtils getInstance() {
return LambdaUtils.INSTANCE;
}
public <K> K getEntryKey(Entry<K, ?> entry) {
return entry.getKey();
}
public <V> V getEntryValue(Entry<?, V> entry) {
return entry.getValue();
}
}
The problem is that now I don't know how to add that call to the utility class methods inside the lambda.
final Map<String, UserBean> users = persons.entrySet().stream()
.filter(entry -> !entry.getValue().getIsActive().booleanValue())
.collect(Collectors.toMap(
this::LambdaUtils.getInstance().getEntryKey() //ERROR
, entry -> entry.getValue()));
How can I make the call to that external method inside a lambda?
I think you're making your life too complicated. From the oracle documentation on method references you can extract a table that explains what types of references can be used and their syntax:
In your case you want to extract key and value from your inputs, so I suggest you use the third option of the table with type
Map.Entry
: