大家好,我是大华!在日常Java开发中,我们经常会遇到一些让人眼前一亮的编程技巧,这些代码不仅简洁,还能大幅提升开发效率。
1. 使用Stream API进行函数式集合操作
Java8引入的Stream API让我们能用更声明式的方式处理集合数据。
传统写法:
List numbers = Arrays.asList(1, 2, 3, 4, 5);
List filteredNumbers = new ArrayList();
for (Integer num : numbers) {
if (num > 2) {
filteredNumbers.add(num);
}
}
现代写法:
List filteredNumbers = numbers.stream()
.filter(num -> num > 2)
.collect(Collectors.toList());
常用操作:
// 分组操作
Map<String, List> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
// 统计操作
IntSummaryStatistics stats = numbers.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
// 去重并排序
List uniqueSorted = list.stream()
.distinct()
.sorted()
.collect(Collectors.toList());
优势:
1.代码更简洁易读
2.业务逻辑与迭代逻辑分离
3.支持并行处理
使用建议:
适合:数据过滤、转换、聚合等操作;
不适合:需要直接操作索引的场景;
大数据集可考虑使用parallelStream()。
2. 使用Optional避免空指针异常
Optional让空值处理变得更优雅,减少深层null检查。
传统写法:
public String getCityName(User user) {
if (user != null && user.getAddress() != null
&& user.getAddress().getCity() != null) {
return user.getAddress().getCity().getName();
}
return \"未知\";
}
现代写法:
public String getCityName(User user) {
return Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.map(City::getName)
.orElse(\"未知\");
}
更安全的用法:
// 避免使用 get(),推荐以下方式:
String value = optional.orElse(\"默认值\");
String value = optional.orElseGet(() -> computeDefault()); // 延迟计算
optional.ifPresent(val -> process(val)); // 存在时执行
// 链式异常处理
String result = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.orElseThrow(() -> new IllegalArgumentException(\"用户信息不完整\"));
使用建议:
适合:方法返回值可能为null的情况;
不适合:集合类返回值(应返回空集合);
性能敏感场景需谨慎使用。
3. 使用Try-With-Resources自动资源管理
自动管理资源释放,让代码更安全简洁。
传统写法:
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(\"file.txt\"));
// 使用资源
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
现代写法:
try (BufferedReader br = new BufferedReader(new FileReader(\"file.txt\"))) {
// 使用资源
} catch (IOException e) {
e.printStackTrace();
}
处理多个资源:
try (InputStream input = new FileInputStream(\"source\");
OutputStream output = new FileOutputStream(\"target\")) {
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
使用建议:
适合:文件、网络连接、数据库连接等资源。
资源类必须实现AutoCloseable接口。
4. 使用模式匹配简化类型检查
Java16引入的模式匹配让类型检查和转换更简洁。
传统写法:
if (obj instanceof String) {
String str = (String) obj; // 需要显式转换
return str.toUpperCase();
} else if (obj instanceof Integer) {
Integer num = (Integer) obj; // 需要显式转换
return num.toString();
}
现代写法:
if (obj instanceof String str) {
return str.toUpperCase(); // str自动转换为String类型
} else if (obj instanceof Integer num) {
return num.toString(); // num自动转换为Integer类型
}
switch表达式结合(Java 17+):
return switch (obj) {
case String str -> \"字符串: \" + str;
case Integer num -> \"整数: \" + num;
case Double d -> \"浮点数: \" + d;
case null -> \"空值\";
default -> \"未知类型\";
};
优势:
1.减少样板代码
2.避免错误的类型转换
3.代码更清晰
5. 使用CompletableFuture进行异步编程
让异步编程变得更直观,支持链式调用。
基础用法:
// 简单的异步任务
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
return \"处理结果\";
});
// 链式处理
CompletableFuture processed = future
.thenApply(result -> result + \" - 已处理\")
.thenApply(String::toUpperCase);
// 获取结果
processed.thenAccept(System.out::println);
组合多个任务:
CompletableFuture task1 = CompletableFuture.supplyAsync(() -> \"结果1\");
CompletableFuture task2 = CompletableFuture.supplyAsync(() -> \"结果2\");
// 等待所有任务完成
CompletableFuture allTasks = CompletableFuture.allOf(task1, task2);
allTasks.thenRun(() -> {
System.out.println(\"所有任务完成!\");
});
异常处理:
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException(\"随机错误\");
}
return \"成功\";
}).exceptionally(ex -> {
System.out.println(\"处理异常: \" + ex.getMessage());
return \"默认值\";
});
// 超时控制(Java 9+)
future.completeOnTimeout(\"超时默认值\", 1, TimeUnit.SECONDS);
优势:
1.非阻塞的异步编程
2.支持任务组合和链式调用
3.更好的异常处理机制
总结
| 技巧 | 核心优势 | 适用场景 |
|---|---|---|
| Stream API | 声明式集合操作 | 数据过滤、转换、聚合 |
| Optional | 安全的空值处理 | 方法返回值可能为null |
| Try-With-Resources | 自动资源管理 | 文件、网络、数据库连接 |
| 模式匹配 | 简化类型检查 | instanceof检查后的类型转换 |
| CompletableFuture | 优雅的异步编程 | 并行任务、异步处理 |
最佳实践建议:
1.Stream API:优先使用声明式操作,大数据集考虑并行流
2.Optional:主要用于返回值,避免直接调用get()方法
3.Try-With-Resources:所有需要关闭的资源都应使用此语法
4.模式匹配:Java 16+项目可积极采用
5.CompletableFuture:适合IO密集型任务,避免在计算密集型任务中过度使用
这些技巧能让我们的代码更简洁、更安全、更易维护!
往期精彩
《这20条SQL优化方案,让你的数据库查询速度提升10倍》
《MySQL 为什么不推荐用雪花ID 和 UUID 做主键?》
《无需UI库!50行CSS打造丝滑弹性动效导航栏,拿来即用》
《SpringBoot3+Vue3实现的数据库文档工具,自动生成Markdown/HTML》



还没有评论呢,快来抢沙发~