Java
Cheat Sheet

Classes, interfaces, streams, collections, and concurrency patterns. From basics to advanced Java.

Variables & Types

Primitive Types

int x = 42;
double y = 3.14;
String s = "hello";
boolean b = true;
long l = 100L;
float f = 2.5f;

Arrays & Collections

int[] nums = {1, 2, 3};
List<String> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
Set<Integer> set = new HashSet<>();

Classes & Interfaces

Class Definition

public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
}

Interfaces & Records

interface Drawable {
    void draw();
    default void hide() { }
}

record Point(int x, int y) {}

// Sealed interfaces
sealed interface Shape
    permits Circle, Square {}

Lambdas & Streams

Lambda Expressions

// Lambda syntax
Runnable r = () -> System.out.println("hi");
Comparator<Integer> c = (a, b) -> a - b;

// Method references
list.forEach(System.out::println);
list.stream().map(String::toUpperCase);

Stream API

List<String> result = names.stream()
    .filter(n -> n.length() > 3)
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());

int sum = nums.stream()
    .mapToInt(Integer::intValue)
    .sum();

Collections & Common Patterns

Map Operations

Map<String, Integer> map = new HashMap<>();
map.put("key", 42);
int val = map.getOrDefault("missing", 0);

map.computeIfAbsent("k", k -> new ArrayList<>());
map.merge("key", 1, Integer::sum);

Optional & Null Safety

Optional<String> opt = Optional.ofNullable(name);
String val = opt.orElse("default");
String mapped = opt
    .map(String::toUpperCase)
    .orElse("N/A");

Concurrency

Threads & Executors

ExecutorService exec =
    Executors.newFixedThreadPool(4);
exec.submit(() -> doWork());
exec.shutdown();
exec.awaitTermination(10, SECONDS);

Virtual Threads (Java 21+)

Thread.startVirtualThread(() -> {
    // runs on virtual thread
});

try (var exec =
    Executors.newVirtualThreadPerTaskExecutor()) {
    exec.submit(() -> doWork());
}

Download

Print this page or save as PDF for quick reference.

Tip: Use Ctrl+P (Cmd+P on Mac) to print or save as PDF.