Skip to main content

Java Reference

v1.0.2reference

Searchable Java quick reference — collections, streams, concurrency, I/O, records, and patterns.

Quick-reference for Java — covers primitive types, Collections, Streams, Optional, lambdas, String methods, date/time API, and common java.util and java.io patterns with copy-ready code snippets.

How to use
  • Search by class or method name (e.g. "ArrayList", "Stream.filter", "LocalDate") to jump to its entry.
  • Click any code snippet to copy it and adapt it in your Java file.
  • Browse the Streams section for functional pipeline patterns — filter, map, collect, reduce.
  • Use the Concurrency reference for ExecutorService, CompletableFuture, and synchronized patterns.

31 results

List.of()

CollectionsJava 9

static <E> List<E> of(E... elements)

Creates an immutable list containing the given elements.

List<String> names = List.of("Alice", "Bob");

Map.of()

CollectionsJava 9

static <K,V> Map<K,V> of(K k1, V v1, ...)

Creates an immutable map with up to 10 key-value pairs.

Map<String, Integer> m = Map.of("a", 1, "b", 2);

Map.entry()

CollectionsJava 9

static <K,V> Map.Entry<K,V> entry(K key, V value)

Creates an immutable Map.Entry.

var entry = Map.entry("key", "value");

Set.copyOf()

CollectionsJava 10

static <E> Set<E> copyOf(Collection<E> coll)

Returns an unmodifiable set containing the elements of the given collection.

Set<String> copy = Set.copyOf(mutableSet);

Collections.unmodifiableList()

CollectionsJava 2

static <T> List<T> unmodifiableList(List<T>)

Returns an unmodifiable view of the specified list.

var safe = Collections.unmodifiableList(list);

SequencedCollection

CollectionsJava 21

interface SequencedCollection<E>

Collection with defined encounter order — adds reversed(), getFirst(), getLast().

list.reversed().forEach(System.out::println);

stream().filter()

StreamsJava 8

Stream<T> filter(Predicate<? super T> predicate)

Returns a stream of elements matching the given predicate.

list.stream().filter(s -> s.length() > 3).toList();

stream().map()

StreamsJava 8

Stream<R> map(Function<? super T, ? extends R> mapper)

Returns a stream of the results of applying the given function.

names.stream().map(String::toUpperCase).toList();

stream().flatMap()

StreamsJava 8

Stream<R> flatMap(Function<T, Stream<R>>)

One-to-many mapping that flattens the resulting streams.

orders.stream().flatMap(o -> o.getItems().stream()).toList();

Collectors.groupingBy()

StreamsJava 8

Collector groupingBy(Function classifier)

Groups elements by a classifier function into a Map.

Map<String, List<Person>> byCity = people.stream()
  .collect(Collectors.groupingBy(Person::city));

Stream.toList()

StreamsJava 16

default List<T> toList()

Collects stream elements into an unmodifiable list.

var result = stream.filter(x -> x > 0).toList();

Stream.gather()

StreamsJava 24

Stream<R> gather(Gatherer<T,?,R>)

User-defined intermediate stream operations.

stream.gather(windowFixed(3)).toList();

CompletableFuture

ConcurrencyJava 8

class CompletableFuture<T>

A Future that may be explicitly completed, supporting dependent functions and actions.

CompletableFuture.supplyAsync(() -> fetchData())
  .thenApply(String::toUpperCase)
  .thenAccept(System.out::println);

ExecutorService

ConcurrencyJava 5

interface ExecutorService

Manages a pool of threads for async task execution.

var executor = Executors.newFixedThreadPool(4);
executor.submit(() -> process(item));

Virtual Threads

ConcurrencyJava 21

Thread.ofVirtual().start(Runnable)

Lightweight threads for high-throughput concurrent applications.

Thread.ofVirtual().start(() -> handleRequest(req));

StructuredTaskScope

ConcurrencyJava 21 (preview)

class StructuredTaskScope<T>

Structured concurrency: manage multiple tasks as a single unit of work.

try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
  var f1 = scope.fork(() -> fetchUser());
  var f2 = scope.fork(() -> fetchOrders());
  scope.join().throwIfFailed();
}

Files.readString()

I/OJava 11

static String readString(Path path)

Reads entire file content into a String.

String content = Files.readString(Path.of("data.txt"));

Files.writeString()

I/OJava 11

static Path writeString(Path path, CharSequence csq, OpenOption...)

Writes a CharSequence to a file.

Files.writeString(Path.of("out.txt"), "Hello");

Files.lines()

I/OJava 8

static Stream<String> lines(Path path)

Read all lines from a file as a lazy Stream.

Files.lines(Path.of("log.txt"))
  .filter(l -> l.contains("ERROR")).toList();

HttpClient

I/OJava 11

class java.net.http.HttpClient

HTTP/2 client with sync and async support.

var client = HttpClient.newHttpClient();
var resp = client.send(request, BodyHandlers.ofString());

String.formatted()

StringsJava 15

String formatted(Object... args)

Instance method for string formatting.

"Hello, %s! You have %d items.".formatted(name, count);

Text Blocks

StringsJava 15

"""..."""

Multi-line string literals that preserve indentation.

String json = """
  { "name": "Alice" }
  """;

String.strip()

StringsJava 11

String strip()

Removes leading and trailing whitespace (Unicode-aware).

"  hello  ".strip(); // "hello"

Optional.orElseThrow()

OptionalsJava 10

T orElseThrow()

Returns contained value or throws NoSuchElementException.

var user = findUser(id).orElseThrow();

Optional.ifPresentOrElse()

OptionalsJava 9

void ifPresentOrElse(Consumer, Runnable)

Execute action if present, otherwise run empty action.

opt.ifPresentOrElse(
  v -> process(v),
  () -> useDefault()
);

Optional.stream()

OptionalsJava 9

Stream<T> stream()

Converts Optional to a zero-or-one element Stream.

ids.stream()
  .map(this::findUser)
  .flatMap(Optional::stream)
  .toList();

record

Records & SealedJava 16

record Point(int x, int y) {}

Compact data class with auto-generated equals, hashCode, toString.

record User(String name, String email) {}
var u = new User("Alice", "alice@example.com");

sealed class

Records & SealedJava 17

sealed class Shape permits Circle, Rect {}

Restricts which classes can extend/implement a type.

sealed interface Shape permits Circle, Rect {}
record Circle(double r) implements Shape {}

Pattern Matching instanceof

PatternsJava 16

if (obj instanceof Type t) { ... }

Combines instanceof check with variable binding.

if (obj instanceof String s && s.length() > 5) {
  System.out.println(s.toUpperCase());
}

Switch Expressions

PatternsJava 14

var x = switch(val) { case A -> ...; };

Expressions that return a value, with arrow syntax.

String label = switch (status) {
  case ACTIVE -> "Active";
  case INACTIVE -> "Inactive";
};

Pattern Matching switch

PatternsJava 21

switch (obj) { case Type t -> ...; }

Pattern matching in switch statements and expressions.

String fmt = switch (obj) {
  case Integer i -> "int: " + i;
  case String s  -> "str: " + s;
  default -> "other";
};