以下是结合 Java 17+ 新特性的 Java 基础类实操指南,包含核心类库的现代化用法、实战案例及最佳实践:
推荐工具链:
快速配置示例(Maven):
<!-- pom.xml -->
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<release>17</release>
</properties>// Java 17+ 多行字符串
String json = """
{
"name": "Doubao",
"age": 2025
}
""";// 自动装箱/拆箱
Integer num = 100; // 自动装箱
int unwrapped = num; // 自动拆箱
// 数字格式化(Java 12+)
NumberFormat fmt = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
System.out.println(fmt.format(1000000)); // 输出 "1M"// Java 21+ 字符串模板
String name = "World";
String message = STR."Hello, \{name}!";// 字符串与数组互转
String str = "Hello";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
String fromBytes = new String(bytes, StandardCharsets.UTF_8);
// 字符串分割(Java 11+)
String[] parts = "a,b,c".split(",", 2); // [a, b,c]// 创建不可变集合(Java 9+)
List<String> immutableList = List.of("A", "B", "C");
Set<Integer> immutableSet = Set.of(1, 2, 3);
Map<String, Integer> immutableMap = Map.of("one", 1, "two", 2);// 集合过滤与转换
List<String> names = List.of("Alice", "Bob", "Charlie");
List<String> filtered = names.stream()
.filter(name -> name.length() > 4)
.map(String::toUpperCase)
.toList(); // [ALICE, CHARLIE]
// 并行流(适合 CPU 密集型任务)
long count = names.parallelStream()
.filter(name -> name.startsWith("A"))
.count();// Map 计算(Java 8+)
Map<String, Integer> map = new HashMap<>();
map.compute("key", (k, v) -> v == null ? 1 : v + 1);
// List 排序(Java 8+)
List<Integer> numbers = Arrays.asList(3, 1, 4);
numbers.sort(Integer::compareTo); // [1, 3, 4]// Java 14+ 异常处理
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
switch (e.getMessage()) {
case "/ by zero" -> System.err.println("除数不能为零");
default -> e.printStackTrace();
}
}// Java 17+ 限制异常继承
public sealed interface MyException permits SpecificException, AnotherException {
// 接口定义
}// Java 7+ NIO.2 API
Path path = Path.of("data.txt");
// 读取文件(Java 11+)
String content = Files.readString(path, StandardCharsets.UTF_8);
// 写入文件(Java 11+)
Files.writeString(path, "Hello, Doubao!", StandardCharsets.UTF_8);// Java 15+ 异步文件通道
AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
Future<Integer> result = channel.read(ByteBuffer.allocate(1024), 0);以下是一个使用 Java 17+ 特性实现的 CSV 数据分析工具:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DataAnalyzer {
public static void main(String[] args) {
try {
// 读取 CSV 文件
Path path = Path.of("data.csv");
List<String> lines = Files.readAllLines(path);
// 解析数据并计算平均值(跳过表头)
Map<String, Double> avgByCategory = lines.stream()
.skip(1) // 跳过表头
.filter(line -> !line.isEmpty())
.map(line -> line.split(","))
.filter(parts -> parts.length >= 2)
.collect(Collectors.groupingBy(
parts -> parts[0], // 按第一列分组
Collectors.averagingDouble(parts -> Double.parseDouble(parts[1]))
));
// 输出结果
avgByCategory.forEach((category, avg) -> {
System.out.printf("%s: 平均值 = %.2f%n", category, avg);
});
} catch (IOException e) {
System.err.println("文件读取错误: " + e.getMessage());
}
}
}StringBuilder 或 Java 17+ 的文本块。ArrayList(initialCapacity) 预分配空间。var 关键字减少冗余类型声明(Java 10+)。jackson-databind)通过上述内容,你可以快速掌握 Java 基础类的现代用法,并结合实际案例进行开发实践。建议在 IDE 中创建一个 Maven 项目,逐步实现上述代码片段,加深对 Java 核心类库的理解。
Java 基础,Java 入门,Java 类,面向对象编程,Java 实操,Java 开发,Java 核心类库,异常处理,集合框架,多线程,IO 流,Java 反射,Java 注解,Java 泛型,Java 编程思想
资源地址:
https://pan.quark.cn/s/14fcf913bae6
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。