如何解决使用 .apply 引用方法
class Racer {
private String name;
private String teamName;
// and getters
}
我正在使用 а 方法来查找列表中字段的最大长度:
int maxRacerNameLength = getMaxFieldLength(racers,Racer::getName);
int maxTeamNameLength = getMaxFieldLength(racers,Racer::getTeamName);
方法实现:
private int getMaxFieldLength(List<Racer> racers,Function<Racer,String> getter) {
return racers.stream().mapToInt(racer -> getter.apply(racer).length()).max().getAsInt();
}
解决方法
您可以通过将 IdentityUser
分成两步来实现:
mapToInt(racer->getter.apply(racer).length())
演示:
return racers.stream().map(getter::apply).mapToInt(String::length).max().getAsInt();
输出:
public class Main {
public static void main(String[] args) {
List<Racer> racers = List.of(
new Racer("Andy","One"),new Racer("Thomas","Four"),new Racer("John",new Racer("Newton","Four")
);
System.out.println(getMaxFieldLength(racers,Racer::getName));
System.out.println(getMaxFieldLength(racers,Racer::getTeamName));
}
static int getMaxFieldLength(List<Racer> racers,Function<Racer,String> getter) {
return racers.stream().map(getter::apply).mapToInt(String::length).max().getAsInt();
}
}
方法引用的种类:
亲切 | 示例 |
---|---|
引用静态方法 | ContainingClass::staticMethodName |
引用特定对象的实例方法 | 包含Object::instanceMethodName |
引用特定类型的任意对象的实例方法 | ContainingType::methodName |
对构造函数的引用 | ClassName::new |
从Method References了解更多信息。
,您可以通过以下方式实现您想要的:
private int getMaxFieldLength(List<Racer> racers,String> getter) {
return racers.stream()
.map(getter)
.mapToInt(String::length)
.max()
.getAsInt();
}
但是,我不建议使用 OptionalInt
获取 getAsInt
的值。那是一个滑坡。赛车手列表可能为空,这将导致 NoSuchElementException
。
在这种情况下,您应该返回一个默认值(这里 0 似乎没问题):
private int getMaxFieldLength(List<Racer> racers,String> getter) {
return racers.stream()
.map(getter)
.mapToInt(String::length)
.max()
.orElse(0);
}
或者返回 OptionalInt
并让方法调用者处理它:
private OptionalInt getMaxFieldLength(List<Racer> racers,String> getter) {
return racers.stream()
.map(getter)
.mapToInt(String::length)
.max();
}
,
如果实现必须始终找到 int
egers 流的最大值,那么您可能更喜欢 ToIntFunction
而不是 Function<Racer,String>
。这会将方法的实现和签名更改为:
private int getMaxFieldLength(List<Racer> racers,ToIntFunction<Racer> toLength) {
return racers.stream()
.mapToInt(toLength)
.max()
.orElse(Integer.MIN_VALUE); // or throw exception for empty racers
}
这将反过来使用该方法:
int maxRacerNameLength = getMaxFieldLength(racers,racer -> racer.getName().length());
int maxTeamNameLength = getMaxFieldLength(racers,racer -> racer.getTeamName().length());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。