本文介绍如何利用 Java 8 的 Lambda 表达式和 Map 数据结构,优雅地重构包含大量 if 语句的代码,特别是针对对象字段的非空校验场景。通过将校验逻辑与字段关联,可以简化代码结构,提高代码的可读性和可维护性,并方便后续扩展。
在处理对象字段校验时,传统的 if 语句方式可能会导致代码冗长且难以维护。Java 8 引入的 Lambda 表达式和 Map 数据结构提供了一种更简洁、更灵活的解决方案。
核心思想: 将字段名与对应的校验函数(Lambda 表达式)存储在 Map 中,然后遍历 Map,对每个字段执行校验。
示例:
立即学习“Java免费学习笔记(深入)”;
假设我们有一个 User 类,需要校验其 name、lastName、dni 和 vehicle 字段是否为空。
public class User { private String name; private String lastName; private String dni; private String vehicle; // Getters and setters public String getName() { return name; } public String getLastName() { return lastName; } public String getDni() { return dni; } public String getVehicle() { return vehicle; } public void setName(String name) { this.name = name; } public void setLastName(String lastName) { this.lastName = lastName; } public void setDni(String dni) { this.dni = dni; } public void setVehicle(String vehicle) { this.vehicle = vehicle; } }
重构后的代码:
import java.util.Map; import java.util.function.Function; public class UserValidator { private static final Map<String, Function<User, ?>> VALIDATIONS = Map.of( "name", User::getName, "lastName", User::getLastName, "dni", User::getDni, "vehicle", User::getVehicle ); public void validateUserFields(User user) { VALIDATIONS.entrySet().stream() .filter(entry -> entry.getValue().apply(user) == null) .map(Map.Entry::getKey) .map(field -> String.format("The user's %s cannot be null", field)) .map(RuntimeException::new) .findFirst() .ifPresent(e -> { throw e; }); } public static void main(String[] args) { User user = new User(); user.setName("John"); user.setLastName("Doe"); // user.setDni("123456789"); // DNI is null user.setVehicle("Car"); UserValidator validator = new UserValidator(); try { validator.validateUserFields(user); System.out.println("User is valid."); } catch (RuntimeException e) { System.out.println("Validation failed: " + e.getMessage()); } } }
代码解释:
VALIDATIONS Map: 定义一个 Map
validateUserFields 方法:
更简洁的版本:
import java.util.Map; import java.util.function.Function; public class UserValidator { private static final Map<String, Function<User, ?>> VALIDATIONS = Map.of( "name", User::getName, "lastName", User::getLastName, "dni", User::getDni, "vehicle", User::getVehicle ); public void validateUserFields(User user) { VALIDATIONS.entrySet().stream() .filter(entry -> entry.getValue().apply(user) == null) .findFirst() .ifPresent(e -> { throw new RuntimeException("The user's " + e.getKey() + " cannot be null"); }); } }
这个版本避免了多次 .map() 操作,直接在 .ifPresent() 中构建异常信息。
优点:
注意事项:
总结:
使用 Java 8 的 Lambda 表达式和 Map 数据结构可以有效地重构包含大量 if 语句的代码,提高代码的可读性、可维护性和可扩展性。 这种方法特别适用于对象字段校验等场景。 通过将校验逻辑与字段关联,可以简化代码结构,使代码更加清晰和易于理解。
以上就是使用 Java 8 Lambdas 和 Map 重构 If 语句的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号