JAVA

Java Cheatsheet

Core Java syntax - classes, collections, and the Stream API used in modern Java code.

Basics

public class Foo { }

Class declaration

List<Integer> list = new ArrayList<>();

Resizable list

Map<String, Integer> map = new HashMap<>();

Key-value map

public static void main(String[] args)

Program entry point

int[] arr = {1, 2, 3};

Array literal

Streams

list.stream().filter(x -> x > 0)

Filter a stream

list.stream().map(x -> x * 2)

Transform each element

list.stream().collect(Collectors.toList())

Collect a stream into a list

list.stream().reduce(0, Integer::sum)

Reduce a stream to a single value

Control flow

for (int i = 0; i < 10; i++)

Standard for loop

for (String s : list)

Enhanced for-each loop

try { } catch (Exception e) { }

Exception handling

switch (x) { case 1 -> ...; }

Switch expression (Java 14+)