我有一个任务,我需要将以下 Java 8 之前的代码转换为 Java 8 代码。以下只是一种让我很难完成的方法:
public static List<VehicleMake> loadMatching(Region region, String nameStartsWith, VehicleLoader loader) {
if ((nameStartsWith == null) || (region == null) || (loader == null)) {
throw new IllegalArgumentException("The VehicleLoader and both region and nameStartsWith are required when loading VehicleMake matches");
}
List<VehicleMake> regionMakes = loader.getVehicleMakesByRegion(region.name());
if (regionMakes == null) {
return null;
}
List<VehicleMake> matches = new ArrayList<>(regionMakes.size());
for (VehicleMake make : regionMakes) {
if ((make.getName() == null) || !make.getName().startsWith(nameStartsWith)) {
continue;
}
matches.add(make);
}
return matches;
}
我想通过使用Optional<T>
而不修改以前创建的类和接口来删除空检查。
我尝试通过更改方法返回类型并执行以下操作开始,但编译器抛出此错误:
Bad return type in method reference
因为 VehicleMake 类没有可选的实例字段。
以下是我的代码尝试:
public static Optional<List<VehicleMake>> loadMatchingJava8(Region region, String nameStartsWith, VehicleLoader loader) {
Optional<List<VehicleMake>> regionMakes = Optional.ofNullable(loader).ifPresent(loader.getVehicleMakesByRegion(Optional.ofNullable(region).ifPresent(region.name())));
/*
TODO rest of the conversion
*/
}
编辑:通过不将参数传递给方法引用来删除flatMap
和更正的代码。但现在它不让我region.name()
通过getVehicleMakesByRegion()
编辑:将消费者传递给ifPresent()
:
Optional<List<VehicleMake>> regionMakes = Optional.ofNullable(loader).ifPresent(()-> loader.getVehicleMakesByRegion(Optional.ofNullable(region).ifPresent(()->region.name()));