DM
Technical reference

Java Cheatsheet

Object-oriented programming on the JVM

Must Know

java

Record

Records are concise immutable data carriers.

public record User(long id, String name) {}
java

Collections

Program to collection interfaces.

List<String> names = new ArrayList<>();
Map<Long, User> users = new HashMap<>();
Set<String> roles = new HashSet<>();

Important Patterns

java

Try with Resources

AutoCloseable resources close even on failure.

try (var reader = Files.newBufferedReader(path)) {
    return reader.lines().toList();
}
java

Optional

Use Optional for return values, not fields or parameters.

return repository.find(id)
    .map(UserDto::from)
    .orElseThrow(NotFoundException::new);

Useful Recipes

java

Stream Pipeline

var activeNames = users.stream()
    .filter(User::active)
    .map(User::name)
    .sorted()
    .toList();
java

Executor

Bound concurrency around constrained downstream resources.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    var future = executor.submit(() -> client.fetch());
    return future.get();
}

Pitfalls & Production

java

Equality Contract

Objects used as map keys need consistent equality and hashing.

@Override public boolean equals(Object other) { ... }
@Override public int hashCode() { ... }
java

Exceptions

Use specific exceptions and preserve diagnostic context.

throw new OrderNotFoundException(orderId);
// Preserve the cause: new ServiceException("Failed", cause)