Java-cheatsheet
Een doorzoekbaar, afdrukbaar Java-naslagwerk: types, strings, collections, streams, records, pattern matching, concurrency en file I/O. Gratis.
Basics & types
10var list = new ArrayList<String>();
int x = 42; double d = 3.14;
long big = 9_000_000_000L;
char c = 'A'; boolean ok = true;
final int MAX = 100;
int i = (int) 3.99;
double d = x;
int n = Integer.parseInt("42");
String s = String.valueOf(42);
Integer boxed = 42; int y = boxed;
Strings & text blocks
12s.length(); s.charAt(0);
s.substring(1, 3)
s.contains("x"); s.startsWith("a");
s.replace("a", "b")
s.strip()
s.split(",")
String.join(", ", parts)
"ab".repeat(3)
s.isBlank(); s.isEmpty();
"%s: %d".formatted(key, count)
String html = """\n <p>Hi</p>\n """;
new StringBuilder().append(a).append(b)
Collections
12List<String> l = List.of("a", "b");
Map<String, Integer> m = Map.of("a", 1);
Set<Integer> s = Set.of(1, 2, 3);
new ArrayList<>(List.of("a", "b"))
List.copyOf(list)
map.getOrDefault(key, 0)
map.computeIfAbsent(k, x -> new ArrayList<>())
map.merge(key, 1, Integer::sum)
list.removeIf(s -> s.isBlank())
list.sort(Comparator.naturalOrder())
for (var e : map.entrySet())
list.forEach(System.out::println)
Streams & lambdas
12list.stream().map(String::toUpperCase).toList()
.filter(n -> n > 0)
.sorted(Comparator.comparing(User::name))
.distinct().limit(10).skip(5)
.collect(Collectors.groupingBy(User::city))
.collect(Collectors.joining(", "))
.collect(Collectors.toMap(User::id, u -> u))
.flatMap(List::stream)
.mapToInt(Order::total).sum()
.reduce(0, Integer::sum)
.anyMatch(s -> s.isBlank())
IntStream.range(0, 10)
Records & sealed classes
9record Point(int x, int y) {}
var p = new Point(1, 2); p.x();
equals(), hashCode(), toString()
record Range(int lo, int hi) { Range { if (lo > hi) throw new IllegalArgumentException(); } }
record Point(...) implements Shape {}
static Point origin() { return new Point(0, 0); }
sealed interface Shape permits Circle, Square {}
final class Circle implements Shape {}
non-sealed class Square implements Shape {}
Pattern matching & switch
8if (obj instanceof String s) use(s);
int n = switch (day) { case MON -> 1; default -> 0; };
case MON, TUE -> "early week";
case X -> { ...; yield value; }
case String s when s.length() > 2 ->
case Point(int x, int y) -> x + y;
case null, default -> "none";
switch (shape) { case Circle c -> ... }
OOP essentials
11interface Greeter { default String hi() { return "hi"; } }
class Impl implements A, B {}
class Admin extends User {}
@Override public String toString()
super.method(); super(args);
class Box<T> { T value; }
<T extends Comparable<T>> T max(...)
List<? extends Number> nums
enum Status { ACTIVE, DONE }
abstract class Base { abstract void run(); }
public static User of(String n) { ... }
Optional
10Optional.of(v); Optional.empty();
Optional.ofNullable(maybeNull)
opt.isPresent(); opt.isEmpty();
opt.orElse(defaultValue)
opt.orElseGet(() -> compute())
opt.orElseThrow()
opt.map(User::name).filter(n -> !n.isBlank())
opt.ifPresent(v -> use(v))
opt.ifPresentOrElse(use, this::warn)
opt.get()
Exceptions & try-with-resources
9try { ... } catch (IOException e) { ... }
catch (IOException | SQLException e)
finally { cleanup(); }
try (var in = Files.newBufferedReader(p)) { ... }
throw new IllegalArgumentException("bad id");
class AppException extends RuntimeException {}
RuntimeException vs Exception
e.getMessage(); e.getCause();
Objects.requireNonNull(x, "x is required")
Concurrency
12Thread.startVirtualThread(() -> work());
Executors.newVirtualThreadPerTaskExecutor()
var pool = Executors.newFixedThreadPool(4);
Future<T> f = pool.submit(task); f.get();
CompletableFuture.supplyAsync(() -> fetch())
.thenApply(r -> parse(r))
.thenCombine(other, (a, b) -> a + b)
.exceptionally(e -> fallback)
CompletableFuture.allOf(f1, f2).join();
new AtomicInteger().incrementAndGet()
new ConcurrentHashMap<K, V>()
synchronized (lock) { ... }
I/O & files (java.nio)
12Path p = Path.of("data", "file.txt");
String s = Files.readString(p);
Files.writeString(p, text);
List<String> lines = Files.readAllLines(p);
try (var st = Files.lines(p)) { ... }
Files.exists(p); Files.size(p);
Files.createDirectories(dir);
Files.copy(src, dst); Files.move(src, dst);
Files.deleteIfExists(p);
try (var files = Files.list(dir)) { ... }
Files.walk(dir)
Files.createTempFile("up-", ".tmp")
Build & CLI
12javac Main.java && java Main
java Main.java
java -jar app.jar
java -Xmx512m -jar app.jar
jshell
mvn clean package
mvn test
mvn dependency:tree
./gradlew build
./gradlew test --tests "UserTest"
jar tf app.jar
java --version
Geen vermelding komt overeen met “:q”.
Over Java-cheatsheet
Deze Java cheat sheet vat modern Java samen op één doorzoekbare pagina: basis en types, strings en text blocks, collections, streams en lambdas, records en sealed classes, pattern matching en switch, OOP-essentials, Optional, exceptions en try-with-resources, concurrency, bestands-I/O met java.nio, en de build- en CLI-commando's.
Hij behandelt zowel de basisprincipes die u dagelijks schrijft (een List, een HashMap, een for-each-lus, een try-with-resources-blok) als de nieuwere taalfuncties die hebben veranderd hoe Java leest, waaronder records, sealed types, switch expressions met pattern matching en text blocks.
De sheet is gratis en client-side: filter rijen live met de zoekbalk, spring tussen secties met de plakkende inhoudsopgave, kopieer elke code met één klik en druk de pagina af als referentie naast uw toetsenbord.
Hoe gebruik je Java-cheatsheet
- Blader door de secties, van Basics & types en Collections via Concurrency tot Build & CLI.
- Zoek op een trefwoord zoals stream, record of Optional om elke rij live te filteren.
- Ga naar Pattern matching & switch of Streams & lambdas wanneer u de moderne syntax nodig heeft.
- Klik op een codefragment of het kopieerpictogram om de Java-code naar uw klembord te kopiëren.
- Druk de sheet af voor een offline Java-referentie.