Pular para o conteúdo
Snippets·Grátis

Snippets de Java

20 snippets de Java: records com validação, expressões switch e pattern matching, streams e Collectors, Optional, try-with-resources, threads virtuais, java.net.http e testes JUnit 5. Alguns precisam do Java 17 ou 21.

Instalação grátis.

Se o PocketCode estiver instalado no seu Android, isto abre a página no app.

Prévia

5 de 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}));

Mudanças na 1.0.0

Primeira versão.

Relacionados