Java 地图的方法参考 - IntelliJ 警告
Java method reference for map - IntelliJ warning
Intellij 警告这个表达式:
usersAttributes.get(user.getName()).forEach((attrName, val) -> user.addAttribute(attrName, val));
可以用方法引用代替。我该怎么做?
IntelliJ 是对的。您可以重写:
usersAttributes.get(user.getName()).forEach(user::addAttribute);
这种method reference is called "Reference to an instance method of a particular object":
The following is an example of a reference to an instance method of a particular object:
class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
The method reference myComparisonProvider::compareByName
invokes the method compareByName
that is part of the object myComparisonProvider
. The JRE infers the method type arguments, which in this case are (Person, Person)
.
在你的例子中,user::addAttribute
指的是名为 addAttribute
的方法采用两个参数,其中第一个与 attrName
的类型兼容,第二个也与类型兼容val
。此方法将在 user
实例上调用。
Intellij 警告这个表达式:
usersAttributes.get(user.getName()).forEach((attrName, val) -> user.addAttribute(attrName, val));
可以用方法引用代替。我该怎么做?
IntelliJ 是对的。您可以重写:
usersAttributes.get(user.getName()).forEach(user::addAttribute);
这种method reference is called "Reference to an instance method of a particular object":
The following is an example of a reference to an instance method of a particular object:
class ComparisonProvider { public int compareByName(Person a, Person b) { return a.getName().compareTo(b.getName()); } public int compareByAge(Person a, Person b) { return a.getBirthday().compareTo(b.getBirthday()); } } ComparisonProvider myComparisonProvider = new ComparisonProvider(); Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
The method reference
myComparisonProvider::compareByName
invokes the methodcompareByName
that is part of the objectmyComparisonProvider
. The JRE infers the method type arguments, which in this case are(Person, Person)
.
在你的例子中,user::addAttribute
指的是名为 addAttribute
的方法采用两个参数,其中第一个与 attrName
的类型兼容,第二个也与类型兼容val
。此方法将在 user
实例上调用。