Reference · 53 entries

Java Reference

The Java reference: String, List, Map, Stream API and Optional methods with signatures, the Java version that added each, and complete example programs with their real output.

Java 25 (LTS) Version history

Every example is a complete program compiled and run on Java 25, the current long-term-support release, and each page shows the Java version that introduced the method, linked to the Java version history.

String Methods

Java String methods: length(), charAt(), substring(), indexOf(), split(), join(), strip(), equals(), formatted() and more, with signatures and complete programs that run.

NameDescription
string.length()Return the number of characters (UTF-16 code units) in a string. An empty string has length 0.
string.charAt()Return the character at an index (0-based). Throws StringIndexOutOfBoundsException for an invalid index.
string.substring()Return part of a string from a start index up to (not including) an end index. The original is unchanged.
string.indexOf()Return the index of the first occurrence of a character or substring, or -1 if it isn't found.
string.contains()Return true if the string contains a sequence of characters. Case-sensitive.
string.startsWith()Return true if the string begins with a prefix. endsWith() checks the end the same way.
string.toUpperCase()Return a copy of the string in upper case. toLowerCase() does the opposite.
string.strip()Remove leading and trailing whitespace, including Unicode spaces. Prefer it to the older trim().
string.isBlank()Return true if the string is empty or contains only whitespace. isEmpty() is true only for "".
string.split()Split a string around matches of a regular expression and return the parts as an array.
String.join()Join strings or a collection of strings into one string, with a separator between them.
string.replace()Replace every occurrence of a character or text with another. replaceAll() uses a regular expression instead.
string.equals()Compare the contents of two strings. Never use == for strings: it compares object identity, not text.
string.compareTo()Compare two strings alphabetically: negative if this comes first, 0 if equal, positive if it comes after.
string.repeat()Return the string repeated n times. Handy for padding, separators and simple text art.
string.formatted()Fill a format string's placeholders such as %s, %d and %.2f with values. Same as String.format().

List and ArrayList Methods

List and ArrayList methods: List.of(), add(), get(), set(), remove(), contains(), indexOf(), sort() and subList(), with the common traps explained and runnable examples.

NameDescription
List.of()Create an immutable list from values. Adding or removing later throws UnsupportedOperationException.
list.add()Append an element to the end of a list, or insert it at an index, shifting later elements right.
list.get()Return the element at an index (0-based). Throws IndexOutOfBoundsException for an invalid index.
list.set()Replace the element at an index and return the old value. The list's size doesn't change.
list.remove()Remove an element by index or by value. With a List<Integer>, remove(1) removes index 1, not the value 1.
list.size()Return the number of elements in a list. isEmpty() is a clearer way to check for zero.
list.contains()Return true if the list holds an element equal to the given one (using equals()). O(n) for ArrayList.
list.indexOf()Return the index of the first element equal to the given one, or -1. lastIndexOf() searches from the end.
list.sort()Sort a list in place with a Comparator, or by natural order when you pass null. Collections.sort() does the same.
list.subList()Return a view of part of a list, from an index up to (not including) another. Changes to the view affect the original.

Map and HashMap Methods

Map and HashMap methods: put(), get(), getOrDefault(), containsKey(), merge(), computeIfAbsent(), entrySet() and Map.of(), with counting and grouping examples.

NameDescription
Map.of()Create an immutable map from key-value pairs (up to 10 pairs; Map.ofEntries() for more). No null keys or values.
map.put()Add a key-value pair, or replace the value if the key already exists. Returns the previous value or null.
map.get()Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls.
map.getOrDefault()Return the value for a key, or a default value if the key isn't present. Avoids null checks.
map.containsKey()Return true if the map has an entry for the key, even when its value is null. O(1) for HashMap.
map.remove()Remove the entry for a key and return its value (or null). remove(key, value) only removes a matching pair.
map.putIfAbsent()Add a key-value pair only if the key is missing (or mapped to null). Returns the existing value otherwise.
map.merge()Combine a value into the map: insert it if the key is missing, otherwise apply a function to the old and new values.
map.computeIfAbsent()Return the value for a key, creating and storing it with a function first if the key is missing. Ideal for grouping.
map.entrySet()Return the map's entries (key-value pairs) for looping over keys and values together.

Stream API

The Java Stream API: filter(), map(), reduce(), sorted(), distinct(), limit(), toList(), anyMatch(), Collectors.joining() and groupingBy(), with runnable examples.

NameDescription
stream.filter()Keep only the elements that match a condition. Intermediate and lazy: nothing runs until a terminal operation.
stream.map()Transform each element with a function and return a stream of the results.
stream.toList()Collect a stream's elements into an unmodifiable List. Shorter than collect(Collectors.toList()).
stream.reduce()Combine all elements into one value with an accumulator function, starting from an identity value.
stream.mapToInt()Map to an IntStream of primitive ints, which has sum(), average(), min(), max() and summaryStatistics().
stream.sorted()Return a stream sorted by natural order or by a Comparator. The source collection is not changed.
stream.distinct()Remove duplicate elements (by equals()), keeping the first occurrence of each, in encounter order.
stream.limit()Keep at most the first n elements. skip(n) drops the first n. Together they paginate a stream.
stream.count()Return the number of elements in the stream (a long). A terminal operation.
stream.anyMatch()Return true if any element matches a condition, stopping at the first match. allMatch() and noneMatch() are similar.
stream.collect(Collectors.joining())Join a stream of strings into one string, with an optional separator, prefix and suffix.
stream.collect(Collectors.groupingBy())Group elements into a Map by a key function, optionally counting or summing each group.

Optional

Java Optional: ofNullable(), orElse(), orElseGet(), map(), ifPresent() and orElseThrow(), for handling values that might be missing without null checks.

NameDescription
Optional.ofNullable()Wrap a value that might be null in an Optional, making 'no value' explicit. Optional.of() rejects null.
optional.orElse()Return the value if present, otherwise a default. orElseGet() computes the default lazily, only when needed.
optional.map()Transform the value inside an Optional if present; an empty Optional stays empty. Chains safely without null checks.
optional.ifPresent()Run an action with the value only if it's present. ifPresentOrElse() also handles the empty case.
optional.orElseThrow()Return the value if present, otherwise throw: NoSuchElementException by default, or an exception you supply.

Was this page helpful?