代码片段·免费
Java 代码片段
20 个 Java 代码片段:带校验的 record、switch 表达式和模式匹配、stream 与 Collectors、Optional、try-with-resources、虚拟线程、java.net.http 和 JUnit 5 测试。部分需要 Java 17 或 21。
免费安装。
如果你的 Android 设备上装了 PocketCode,这会在应用里打开此页面。
预览
20 个中的 5 个
Record with validationrecv
Record whose compact constructor rejects invalid values
public record ${1:Point}(${2:int x, int y}) {
public ${1:Point} {
if (${3:x < 0 || y < 0}) {
throw new IllegalArgumentException("${4:coordinates must be positive}");
}
}
}Switch expressionswexpr
Switch that returns a value, with arrow cases
var ${1:label} = switch (${2:day}) {
case ${3:SATURDAY, SUNDAY} -> ${4:"weekend"};
default -> ${5:"weekday"};
};Try-with-resources readertrywr
Read a file line by line and close it automatically
try (var ${1:reader} = Files.newBufferedReader(Path.of("${2:data.txt}"))) {
String line;
while ((line = ${1:reader}.readLine()) != null) {
$0
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}Stream filter and mapstreamf
Filter and transform a list into a new unmodifiable list (Java 16+)
List<${1:String}> ${2:cleaned} = ${3:items}.stream()
.filter(${4:s -> !s.isBlank()})
.map(${5:String::trim})
.toList();Group by a keygroupby
Collect a stream into a map of lists keyed by a property
Map<${1:String}, List<${2:Person}>> ${3:byCity} = ${4:people}.stream()
.collect(Collectors.groupingBy(${5:Person::city}));1.0.0 的变更
首个版本。