Snippets·Free
Java snippets
20 Java snippets: records with validation, switch expressions and pattern matching, streams and Collectors, Optional, try-with-resources, virtual threads, java.net.http and JUnit 5 tests. Some need Java 17 or 21.
Free to install.
If PocketCode is installed on your Android device, this opens the page in the app.
Preview
5 of 20
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}));Changes in 1.0.0
First version.