Cheat sheet Java
Una referenza Java consultabile e stampabile: tipi, stringhe, collezioni, stream, record, pattern matching, concorrenza e I/O su file. 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
Nessuna voce corrisponde a “:q”.
Informazioni su Cheat sheet Java
Questo cheat sheet Java comprime il Java moderno in un'unica pagina consultabile: basi e tipi, stringhe e text block, collezioni, stream e lambda, record e classi sealed, pattern matching e switch, elementi essenziali OOP, Optional, eccezioni e try-with-resources, concorrenza, I/O di file con java.nio, e i comandi di build e CLI.
Copre sia i fondamentali che scrivi ogni giorno (una List, una HashMap, un ciclo for-each, un blocco try-with-resources) sia le funzionalità linguistiche più recenti che hanno cambiato il modo di leggere Java, inclusi record, tipi sealed, espressioni switch con pattern matching e text block.
Il foglio è gratuito e lato client: filtra le righe dal vivo con la casella di ricerca, salta tra le sezioni con l'indice fisso, copia qualsiasi frammento con un clic e stampa la pagina come riferimento accanto alla tastiera.
Come usare Cheat sheet Java
- Scorri le sezioni, da Basi e tipi e Collezioni fino a Concorrenza e Build e CLI.
- Cerca una parola chiave come stream, record o Optional per filtrare ogni riga dal vivo.
- Salta a Pattern matching e switch o Stream e lambda quando ti serve la sintassi moderna.
- Fai clic su un frammento o sulla sua icona di copia per copiare il codice Java negli appunti.
- Stampa il foglio per un riferimento Java offline.