01String Methods
Strings are immutable. Every method that "changes" a string returns a NEW string โ the original is unchanged unless you reassign.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| length() | str.length() |
Number of chars (UTF-16 units) |
Counts code units, not code points.
"๐".length() = 2.
|
| charAt() | str.charAt(2) |
Char at index | Throws StringIndexOutOfBoundsException if invalid. |
| indexOf() | str.indexOf("a") |
First index of char/substring |
Returns -1 if not found. Overload:
indexOf(s, from).
|
| lastIndexOf() | str.lastIndexOf("a") |
Last index of char/substring | Searches from end. Returns -1 if not found. |
| substring() | str.substring(2, 5) |
Extract [start, end) | Returns NEW string. End is exclusive. |
| toLowerCase() | str.toLowerCase() |
All chars to lowercase | Use Locale overload for locale-correct (e.g. Turkish 'I'). |
| toUpperCase() | str.toUpperCase() |
All chars to uppercase | Returns NEW string. |
| trim() | str.trim() |
Remove leading/trailing whitespace |
Only strips ASCII โค . Prefer strip().
|
| strip() | str.strip() |
Unicode-aware trim (Java 11+) | Preferred over trim() in modern code. |
| stripLeading() | str.stripLeading() |
Remove leading whitespace only (11+) | Trailing spaces kept. |
| stripTrailing() | str.stripTrailing() |
Remove trailing whitespace only (11+) | Leading spaces kept. |
| replace() | str.replace("a", "b") |
Replace all literal occurrences | No regex โ fast for literals. |
| replaceAll() |
str.replaceAll(regex, repl)
|
Replace all regex matches | Special regex chars need escaping. |
| replaceFirst() |
str.replaceFirst(regex, repl)
|
Replace first regex match | Regex-based. |
| contains() | str.contains("hi") |
Substring presence | Case-sensitive. No regex. |
| startsWith() | str.startsWith("Hi") |
Prefix check |
Overload: startsWith(prefix, offset).
|
| endsWith() | str.endsWith("!") |
Suffix check | Case-sensitive. |
| equals() | str.equals(other) |
Content equality |
ALWAYS use this, not ==.
|
| equalsIgnoreCase() |
str.equalsIgnoreCase(other)
|
Case-insensitive equality | Null arg throws NPE. |
| compareTo() | str.compareTo(other) |
Lexicographic compare | <0, 0, >0. Used by sort. |
| compareToIgnoreCase() |
str.compareToIgnoreCase(other)
|
Case-insensitive compare | For alphabetic sort regardless of case. |
| isEmpty() | str.isEmpty() |
Length is 0 | Doesn't catch whitespace-only. |
| isBlank() | str.isBlank() |
Empty or whitespace-only (11+) | Better than isEmpty() for input validation. |
| split() | str.split(",") |
Split on regex |
Trailing empties dropped. Use split(r,-1) to
keep.
|
| toCharArray() | str.toCharArray() |
Convert to char[] | Returns NEW array โ modifying it doesn't change string. |
| valueOf() | String.valueOf(42) |
Any value โ String (static) |
valueOf(null) returns "null" โ no NPE.
|
| format() |
String.format("%s %d", s, n)
|
Printf-style format (static) | Specifiers: %s, %d, %f, %n, %tF (date)โฆ |
| concat() | str.concat(" world") |
Append a string |
Prefer + or StringBuilder for multiple
concats.
|
| intern() | str.intern() |
Canonical from string pool | Memory dedup. Use sparingly โ pool is global. |
| matches() | str.matches(regex) |
Whole-string regex match |
Implicitly anchored ^โฆ$. For partial use
find().
|
| repeat() | str.repeat(3) |
Repeat n times (Java 11+) |
repeat(0) = "". Negative throws.
|
| chars() | str.chars() |
IntStream of chars |
Cast: .mapToObj(c -> (char)c).
|
| codePoints() NEW | str.codePoints() |
IntStream of Unicode code points | Handles surrogate pairs (emoji etc.) correctly. |
| codePointAt() | str.codePointAt(0) |
Code point at index |
Use over charAt() for non-BMP chars.
|
| codePointCount() NEW |
str.codePointCount(0, len)
|
Count of code points in range |
Different from length() for emoji/CJK.
|
| getBytes() |
str.getBytes(StandardCharsets.UTF_8)
|
Encode to byte[] | ALWAYS pass a charset for portability. |
| hashCode() | str.hashCode() |
String hash | Equal strings โ equal hash. Cached after first call. |
| toString() | str.toString() |
Returns itself | Useful via Object reference. |
| join() |
String.join("-", "a", "b")
|
Join with delimiter (static) |
Also accepts Iterable:
String.join(", ", list).
|
| formatted() โ |
"Hi %s".formatted(name)
|
Instance format() (Java 15+) |
Cleaner than String.format().
|
| lines() | str.lines() |
Stream<String> of lines (11+) | Splits on \n, \r, \r\n. No terminators in result. |
| indent() โ | str.indent(4) |
Add/remove indentation (12+) | Negative removes spaces. |
| stripIndent() โ | str.stripIndent() |
Strip common indent (15+) | For text blocks. Removes incidental whitespace. |
| translateEscapes() โ |
str.translateEscapes()
|
Translate \n etc. (15+) | Processes escape sequences in literal text. |
| describeConstable() NEW |
str.describeConstable()
|
Optional constant desc (12+) |
For invokedynamic/CDS use; rarely needed.
|
02StringBuilder Methods
Mutable โ methods modify in-place and return
this so they chain. Prefer over
String + in loops.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| append() | sb.append("x") |
Append to end |
Overloads for every type. Chains:
sb.append("a").append("b").
|
| insert() | sb.insert(2, "Hi") |
Insert at index | Shifts existing chars right. |
| delete() | sb.delete(1, 4) |
Remove [start, end) | In-place. End is exclusive. |
| deleteCharAt() | sb.deleteCharAt(3) |
Remove single char | In-place. |
| replace() |
sb.replace(1, 4, "XY")
|
Replace range with string | Replacement length can differ from range. |
| reverse() | sb.reverse() |
Reverse in-place | Handles surrogate pairs correctly. |
| toString() | sb.toString() |
Snapshot to immutable String | Builder itself unchanged. |
| length() | sb.length() |
Current content length |
Different from capacity().
|
| charAt() | sb.charAt(2) |
Char at index | Throws StringIndexOOB. |
| setCharAt() | sb.setCharAt(2, 'Z') |
Set char at index (void) | In-place. Returns nothing. |
| indexOf() | sb.indexOf("ab") |
First index of substring | Returns -1 if missing. |
| lastIndexOf() | sb.lastIndexOf("ab") |
Last index of substring | Returns -1 if missing. |
| substring() | sb.substring(2) |
Substring as new String | Builder unchanged. |
| capacity() | sb.capacity() |
Current buffer size | Default 16. Grows as needed. |
| ensureCapacity() | sb.ensureCapacity(50) |
Pre-grow buffer | Avoids resize churn for known sizes. |
| trimToSize() | sb.trimToSize() |
Shrink buffer to length | Frees unused memory. |
| appendCodePoint() NEW |
sb.appendCodePoint(0x1F600)
|
Append Unicode code point | Correctly encodes surrogate pairs. |
| compareTo() NEW | sb.compareTo(other) |
Lex compare (Java 11+) | Returns <0, 0, >0. |
| chars() NEW | sb.chars() |
IntStream of chars | Same as String.chars(). |
03Array Methods (java.util.Arrays)
All static. sort(), fill(),
setAll() mutate in-place; copyOf(),
copyOfRange() return NEW arrays.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| Arrays.sort() | Arrays.sort(arr) |
Sort ascending in-place | Dual-pivot quicksort (primitives), TimSort (objects). |
| Arrays.sort(range) |
Arrays.sort(arr, 2, 5)
|
Sort sub-range [from, to) | In-place. |
| Arrays.binarySearch() |
Arrays.binarySearch(arr, key)
|
Binary search sorted array | Array MUST be sorted. Negative if missing. |
| Arrays.fill() | Arrays.fill(arr, 0) |
Fill with value | In-place. Range overload available. |
| Arrays.copyOf() | Arrays.copyOf(arr, 6) |
Copy with new length | Pads 0/null if larger. |
| Arrays.copyOfRange() |
Arrays.copyOfRange(arr, 1, 4)
|
Copy sub-range | [from, to). NEW array. |
| Arrays.equals() | Arrays.equals(a, b) |
Element-wise equality | Use this โ arrays don't override equals(). |
| Arrays.deepEquals() |
Arrays.deepEquals(a2d, b2d)
|
Deep equality (nested) | Use for 2D/nested arrays. |
| Arrays.toString() | Arrays.toString(arr) |
Readable [a, b, c] |
arr.toString() gives [I@1b6dโฆ.
|
| Arrays.deepToString() |
Arrays.deepToString(a2d)
|
Readable nested arrays | For 2D arrays. |
| Arrays.asList() |
Arrays.asList(1, 2, 3)
|
Fixed-size list view |
add/remove throw UOE. Wrap in
new ArrayList<>() to make resizable.
|
| Arrays.stream() | Arrays.stream(arr) |
Stream from array | int[] โ IntStream. Range overload exists. |
| Arrays.parallelSort() |
Arrays.parallelSort(arr)
|
Parallel sort (large arrays) | Useful only for >~1000 elements. |
| Arrays.mismatch() | Arrays.mismatch(a, b) |
First differing index (Java 9+) | Returns -1 if equal. |
| Arrays.compare() | Arrays.compare(a, b) |
Lex compare (Java 9+) | <0, 0, >0. |
| arr.length | arr.length |
Length (FIELD, no parens) | Fixed at creation. |
| arr.clone() | arr.clone() |
Shallow copy | For 2D, inner arrays are still shared. |
| Arrays.setAll() NEW |
Arrays.setAll(arr, i -> i*i)
|
Fill via generator function | Cleaner than a manual loop. |
| Arrays.parallelPrefix() NEW |
Arrays.parallelPrefix(arr, Integer::sum)
|
Cumulative reduction in-place | Like prefix sums; parallelized. |
| Arrays.hashCode() NEW | Arrays.hashCode(arr) |
Content-based hash | Use in equals/hashCode of classes containing arrays. |
| Arrays.deepHashCode() NEW |
Arrays.deepHashCode(a2d)
|
Hash for nested arrays | Pairs with deepEquals(). |
04List & ArrayList Methods
ArrayList is mutable. List.of() creates IMMUTABLE
lists. subList() returns a VIEW โ changes
propagate.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| add() | list.add("x") |
Append to end | Returns boolean (always true for ArrayList). |
| add(i, v) | list.add(2, "x") |
Insert at index | O(n) โ shifts right. |
| addAll() | list.addAll(other) |
Append a collection | Modifies in-place. |
| addAll(i, c) NEW | list.addAll(2, other) |
Insert collection at index | Shifts existing elements. |
| get() | list.get(0) |
Element at index | O(1) for ArrayList. |
| set() | list.set(1, "y") |
Replace at index | Returns OLD value. Size unchanged. |
| remove(int) | list.remove(2) |
Remove by index | Returns removed element. O(n) shift. |
| remove(Object) | list.remove("abc") |
Remove first match |
For Integer values use
remove(Integer.valueOf(n)).
|
| clear() | list.clear() |
Remove all | Capacity retained. |
| size() | list.size() |
Element count | Not the same as capacity. |
| isEmpty() | list.isEmpty() |
No elements? | More readable than size()==0. |
| contains() | list.contains("a") |
Membership | O(n). Uses equals(). |
| containsAll() |
list.containsAll(other)
|
All present? | O(n*m). Use Set for speed. |
| indexOf() | list.indexOf("a") |
First match index | -1 if absent. |
| lastIndexOf() | list.lastIndexOf("a") |
Last match index | -1 if absent. |
| subList() | list.subList(1, 4) |
VIEW of [from, to) | Mutations reflect both ways. Wrap in new ArrayList for copy. |
| sort() | list.sort(null) |
Sort with Comparator (or null = natural) | In-place. Stable (TimSort). |
| toArray() |
list.toArray(new String[0])
|
Convert to typed array |
Pass new T[0] โ JVM optimizes.
|
| iterator() | list.iterator() |
Forward iterator |
Use iterator.remove() to remove safely.
|
| listIterator() NEW | list.listIterator() |
Bidirectional + index |
Supports previous(), set(),
add() during iteration.
|
| forEach() |
list.forEach(System.out::println)
|
Lambda iteration | Cannot resize during iteration. |
| removeIf() |
list.removeIf(x -> x > 5)
|
Remove matching predicate | Safe during iteration. |
| replaceAll() |
list.replaceAll(x -> x*2)
|
Transform every element | Size unchanged. |
| retainAll() NEW | list.retainAll(other) |
Keep only common elements | Set intersection on lists. |
| stream() | list.stream() |
Sequential stream | Doesn't modify source. |
| parallelStream() NEW | list.parallelStream() |
Parallel stream | Use only for CPU-bound, large lists. |
| List.of() | List.of(1, 2, 3) |
Immutable list (Java 9+) | Null elements throw NPE. |
| List.copyOf() | List.copyOf(list) |
Immutable snapshot (10+) | Defensive copy. |
05Conversions: Array โ List โ Stream
Common gotcha: Arrays.asList() returns a fixed-size
view. Wrap to make truly resizable.
| Direction | Syntax | Description | Notes |
|---|---|---|---|
| Array โ List (fixed) | Arrays.asList(arr) |
Fixed-size list view | add/remove throw UOE. set() works. |
| Array โ ArrayList |
new ArrayList<>(Arrays.asList(arr))
|
Mutable resizable list | Standard pattern. |
| Array โ List (immut) | List.of(arr) |
Immutable, no nulls | Java 9+. |
| ArrayList โ Array |
list.toArray(new String[0])
|
Typed array | Pass zero-length โ JVM optimizes. |
| List โ ArrayList |
new ArrayList<>(list)
|
Wrap any list as mutable | Defensive copy. |
| Stream โ List |
stream.collect(Collectors.toList())
|
Mutable list |
Java 16+: stream.toList() gives unmodifiable.
|
| Stream โ unmod List | stream.toList() |
Unmodifiable (Java 16+) | Throws on add/remove. |
| int[] โ List<Integer> |
Arrays.stream(arr).boxed().toList()
|
Box primitives |
Can't directly do Arrays.asList(int[]).
|
| List<Integer> โ int[] |
list.stream().mapToInt(x -> x).toArray()
|
Unbox to int[] | mapToInt unboxes. |
| List โ Set |
new HashSet<>(list)
|
Dedupe + lookup O(1) | Loses order. Use LinkedHashSet to preserve. |
| Map โ List of entries NEW |
new ArrayList<>(map.entrySet())
|
Snapshot entries | For sorting/streaming map data. |
06Map & HashMap Methods
HashMap allows one null key + null values. ConcurrentHashMap
forbids both. get()==null is ambiguous โ use
containsKey() or getOrDefault().
| Method | Syntax | Description | Notes |
|---|---|---|---|
| put() | map.put("k", "v") |
Insert or update | Returns PREVIOUS value (or null). |
| get() | map.get("k") |
Lookup | null if absent OR value is null. |
| getOrDefault() |
map.getOrDefault("k", 0)
|
Lookup with fallback | Doesn't insert default. |
| remove() | map.remove("k") |
Remove mapping | Returns removed value. |
| remove(k, v) NEW |
map.remove("k", expected)
|
Conditional remove | Removes only if value matches. |
| containsKey() | map.containsKey("k") |
Key present? | O(1). Disambiguates null values. |
| containsValue() |
map.containsValue("v")
|
Value present? | O(n). Avoid in hot paths. |
| keySet() | map.keySet() |
Set view of keys | Removing affects map. |
| values() | map.values() |
Collection view of values | Not a Set โ duplicates allowed. |
| entrySet() | map.entrySet() |
Set of Map.Entry | Most efficient iteration of both k+v. |
| size() | map.size() |
Mapping count | int. |
| isEmpty() | map.isEmpty() |
No entries? | size()==0. |
| clear() | map.clear() |
Remove all | In-place. |
| putAll() | map.putAll(other) |
Bulk insert/update | Overwrites existing keys. |
| putIfAbsent() |
map.putIfAbsent("k", "v")
|
Insert if missing | Returns existing value if present. |
| replace() |
map.replace("k", "v2")
|
Update if present | Doesn't insert if missing. |
| replace(k, old, new) NEW |
map.replace(k, old, new)
|
CAS-style replace | Only replaces if current value matches. |
| replaceAll() NEW |
map.replaceAll((k, v) -> v.trim())
|
Transform every value | Like List.replaceAll(). |
| merge() |
map.merge("k", 1, Integer::sum)
|
Combine or insert | Counters / accumulators. |
| compute() |
map.compute("k", (k, v) -> v + 1)
|
Recompute value | v may be null. Return null to remove. |
| computeIfAbsent() |
map.computeIfAbsent("k", k -> new
ArrayList<>())
|
Lazy init pattern | Common for "map of lists". |
| computeIfPresent() |
map.computeIfPresent("k", (k, v) -> v + 1)
|
Update if present | Skips missing keys. |
| forEach() |
map.forEach((k, v) -> โฆ)
|
BiConsumer iteration | Cleaner than entrySet loop. |
| Map.of() |
Map.of("a", 1, "b", 2)
|
Immutable map (9+) | Up to 10 pairs. No nulls. |
| Map.ofEntries() NEW |
Map.ofEntries(Map.entry("a", 1), โฆ)
|
Immutable, >10 entries | No size limit. |
| Map.entry() NEW | Map.entry("k", "v") |
Immutable Map.Entry | For ofEntries / collectors. |
| Map.copyOf() | Map.copyOf(map) |
Immutable snapshot (10+) | Defensive copy. |
| Map.Entry.comparingByKey() NEW |
Map.Entry.comparingByKey()
|
Sort entries by key | Use with stream sorting. |
| Map.Entry.comparingByValue() NEW |
Map.Entry.comparingByValue()
|
Sort entries by value | Pair with reversed() for descending. |
07Set, HashSet & TreeSet Methods
HashSet O(1), no order. LinkedHashSet preserves insertion order.
TreeSet sorted, O(log n) โ implements NavigableSet.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| add() | set.add("x") |
Add unique element | Returns false if duplicate. |
| addAll() | set.addAll(coll) |
Union | Returns true if anything added. |
| remove() | set.remove("x") |
Remove element | Returns boolean. |
| removeAll() | set.removeAll(other) |
Set difference | A โ B. |
| retainAll() | set.retainAll(other) |
Set intersection | Keep only A โฉ B. |
| contains() | set.contains("x") |
Membership | O(1) HashSet vs O(n) List. |
| containsAll() |
set.containsAll(other)
|
Subset check | A โ B? |
| size() / isEmpty() / clear() | set.size() |
Standard collection ops | As elsewhere. |
| iterator() | set.iterator() |
Iterate elements | Order: HashSet undefined, LHS insertion, TreeSet sorted. |
| stream() | set.stream() |
Stream of elements | Sequential. |
| Set.of() | Set.of(1, 2, 3) |
Immutable set (Java 9+) | Duplicates throw IAE. |
| Set.copyOf() NEW | Set.copyOf(set) |
Immutable snapshot (10+) | Defensive copy. |
| first() [TreeSet] | treeSet.first() |
Smallest element | NoSuchElement if empty. |
| last() [TreeSet] | treeSet.last() |
Largest element | NoSuchElement if empty. |
| headSet() [TreeSet] | treeSet.headSet("m") |
Strictly less than (view) | Bidirectional propagation. |
| tailSet() [TreeSet] | treeSet.tailSet("m") |
โฅ given value (view) | Inclusive of "m". |
| subSet() [TreeSet] NEW |
treeSet.subSet("a", "m")
|
[from, to) range view | Half-open range. |
| floor() [TreeSet] NEW | treeSet.floor("m") |
Greatest โค given | null if none. |
| ceiling() [TreeSet] NEW | treeSet.ceiling("m") |
Least โฅ given | null if none. |
| lower() [TreeSet] NEW | treeSet.lower("m") |
Greatest < given | Strict. |
| higher() [TreeSet] NEW | treeSet.higher("m") |
Least > given | Strict. |
| pollFirst() [TreeSet] NEW | treeSet.pollFirst() |
Remove and return smallest | null if empty. |
| pollLast() [TreeSet] NEW | treeSet.pollLast() |
Remove and return largest | null if empty. |
| descendingSet() [TreeSet] NEW |
treeSet.descendingSet()
|
Reverse-order view | Iteration is largest-first. |
08Queue & Deque Methods
Prefer offer/poll/peek (return null/false) over
add/remove/element (throw). Use
ArrayDeque instead of legacy Stack.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| offer() | queue.offer("x") |
Insert at tail | Returns false on capacity fail. |
| add() | queue.add("x") |
Insert (throws) | IllegalStateException if full. |
| poll() | queue.poll() |
Remove + return head | null if empty โ preferred. |
| remove() | queue.remove() |
Remove head (throws) | NoSuchElement if empty. |
| peek() | queue.peek() |
View head without removing | null if empty. |
| element() | queue.element() |
View head (throws) | NoSuchElement if empty. |
| offerFirst() [Deque] | deque.offerFirst("x") |
Insert at front | Stack push semantics. |
| offerLast() [Deque] | deque.offerLast("x") |
Insert at end | Same as offer() on a queue. |
| pollFirst() [Deque] | deque.pollFirst() |
Remove from front | null if empty. |
| pollLast() [Deque] | deque.pollLast() |
Remove from end | null if empty. |
| peekFirst() [Deque] | deque.peekFirst() |
View front | null if empty. |
| peekLast() [Deque] | deque.peekLast() |
View end | null if empty. |
| push() [Deque] | deque.push("x") |
Stack push (= addFirst) | Use ArrayDeque as a Stack. |
| pop() [Deque] | deque.pop() |
Stack pop (= removeFirst) | NoSuchElement if empty. |
| addFirst() / addLast() NEW | deque.addFirst(x) |
Insert (throws on capacity) | Throwing variants of offerFirst/Last. |
| removeFirst() / removeLast() NEW | deque.removeFirst() |
Remove (throws) | Use poll-variants if empty is OK. |
| getFirst() / getLast() NEW | deque.getFirst() |
View ends (throws) | peek-variants are safer. |
| descendingIterator() NEW |
deque.descendingIterator()
|
End-to-front iteration | Useful for stack traversal. |
| size() / isEmpty() / contains() | queue.size() |
Standard ops | contains() is O(n). |
09Stack Methods (java.util.Stack)
Legacy class โ synchronizes unnecessarily.
Prefer ArrayDeque for new code.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| push() | stack.push("x") |
Push to top | Returns the pushed element. |
| pop() | stack.pop() |
Remove top | EmptyStackException if empty. |
| peek() | stack.peek() |
View top | EmptyStackException if empty. |
| empty() | stack.empty() |
Empty check |
Quirk: empty() not isEmpty(). Inherits both.
|
| search() | stack.search("x") |
1-based distance from top | -1 if not found. O(n). |
10Collections Utility Methods
All static. sort/reverse/shuffle mutate in-place;
unmodifiable* return read-only VIEWS.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| sort() |
Collections.sort(list)
|
Natural order in-place | Stable. |
| sort(Comp) |
Collections.sort(list, comp)
|
Custom Comparator | Prefer list.sort(comp). |
| reverse() |
Collections.reverse(list)
|
Flip order in-place | Doesn't sort. |
| shuffle() |
Collections.shuffle(list)
|
Random in-place |
Pass Random for reproducibility.
|
| min() / max() | Collections.min(list) |
Smallest / largest | NoSuchElement if empty. |
| frequency() |
Collections.frequency(list, x)
|
Count occurrences | O(n). |
| fill() |
Collections.fill(list, "X")
|
Fill with value | Same reference for all positions. |
| copy() |
Collections.copy(dest, src)
|
Copy src into dest | dest.size() must be โฅ src.size(). |
| swap() |
Collections.swap(list, i, j)
|
Swap two indices | In-place. |
| binarySearch() |
Collections.binarySearch(list, key)
|
Search sorted list | List MUST be sorted. |
| disjoint() |
Collections.disjoint(c1, c2)
|
No common elements? | Returns boolean. |
| addAll() |
Collections.addAll(list, a, b, c)
|
Varargs add | Cleaner than multiple add(). |
| nCopies() |
Collections.nCopies(5, "X")
|
Immutable list of n copies | Same reference reused. |
| singleton() |
Collections.singleton("x")
|
Immutable 1-element Set | No mutation. |
| singletonList() |
Collections.singletonList("x")
|
Immutable 1-element List | More efficient than ArrayList. |
| emptyList() / emptySet() / emptyMap() |
Collections.emptyList()
|
Shared empty constants | Same singleton each call. |
| unmodifiableList() |
Collections.unmodifiableList(list)
|
Read-only VIEW |
Original mutations show through. Use
List.copyOf() for true copy.
|
| unmodifiableMap() / unmodifiableSet() NEW |
Collections.unmodifiableMap(m)
|
Read-only VIEW | Same caveats as List. |
| synchronizedList() |
Collections.synchronizedList(list)
|
Thread-safe wrapper | Iteration still needs explicit sync. Consider CopyOnWriteArrayList. |
| reverseOrder() |
Collections.reverseOrder()
|
Descending Comparator | For natural-order types. |
| rotate() |
Collections.rotate(list, 2)
|
Rotate elements | + right, โ left. |
11Math Methods (java.lang.Math)
All static. PI/E are constant FIELDS
(no parens). Most methods return double.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| abs() | Math.abs(-5) |
Absolute value |
โ ๏ธ Math.abs(Integer.MIN_VALUE) overflows.
|
| max() / min() | Math.max(3, 7) |
Larger / smaller of two | Two-arg only โ chain for more. |
| pow() | Math.pow(2, 8) |
Base ^ exp |
For 2^n use 1L << n โ much faster.
|
| sqrt() / cbrt() | Math.sqrt(16) |
Square / cube root | sqrt(-1) = NaN. cbrt handles negatives. |
| ceil() / floor() | Math.ceil(4.2) |
Round up / down (returns double) | Cast to int if needed. floor is toward โโ. |
| round() | Math.round(4.5) |
Half-up round | Returns long for double, int for float. |
| random() | Math.random() |
Pseudo-random [0, 1) |
For repeatability use java.util.Random.
|
| log() / log10() / exp() | Math.log(Math.E) |
ln / logโโ / e^x | log(0) = โโ, log(neg) = NaN. |
| sin() / cos() / tan() | Math.sin(Math.PI/2) |
Trig in radians | Use toRadians() first. |
| PI / E | Math.PI |
Constants (FIELDS) | No parentheses. |
| signum() | Math.signum(-5.0) |
โ1.0 / 0.0 / 1.0 | Direction normalization. |
| hypot() | Math.hypot(3, 4) |
โ(xยฒ + yยฒ) without overflow | More accurate than manual sqrt. |
| toRadians() / toDegrees() | Math.toRadians(180) |
Angle conversion | 180ยฐ = ฯ rad. |
| floorDiv() / floorMod() | Math.floorDiv(7, 2) |
Floor-rounded div / mod |
-7 % 2 = -1 but
floorMod(-7, 2) = 1.
|
| addExact() / multiplyExact() | Math.addExact(a, b) |
Throws on overflow | Use when correctness matters. |
| subtractExact() NEW |
Math.subtractExact(a, b)
|
Overflow-checked subtract | Throws ArithmeticException. |
| negateExact() / decrementExact() / incrementExact() NEW | Math.negateExact(x) |
Overflow-checked unary ops | Catches MIN_VALUE pitfall. |
| divideExact() NEW |
Math.divideExact(a, b)
|
Overflow-checked div (Java 18+) | Catches MIN_VALUE / -1. |
| toIntExact() NEW |
Math.toIntExact(longValue)
|
Long โ int with check | Throws if doesn't fit. |
| log1p() โ | Math.log1p(x) |
ln(1 + x), accurate for small x | Avoids precision loss vs log(1+x). |
| expm1() โ | Math.expm1(x) |
e^x โ 1, accurate for small x | Pairs with log1p(). |
| fma() NEW | Math.fma(a, b, c) |
Fused multiply-add (Java 9+) | a*b+c with one rounding โ better precision. |
| copySign() NEW |
Math.copySign(magnitude, sign)
|
Apply sign of one to another | Numeric utility. |
| nextUp() / nextDown() NEW | Math.nextUp(x) |
Next representable double | Floating-point neighbor. |
| ulp() NEW | Math.ulp(x) |
Unit in last place | Tolerance for fp comparisons. |
| clamp() NEW | Math.clamp(v, lo, hi) |
Bound between min/max (Java 21+) |
Replaces Math.max(lo, Math.min(hi, v)).
|
12Integer & Wrapper Methods
Wrapper classes bridge primitives and objects. Use
Double.isNaN() not == Double.NaN (NaN
โ NaN).
| Method | Syntax | Description | Notes |
|---|---|---|---|
| parseInt() |
Integer.parseInt("42")
|
String โ int | NFE on bad input. Radix overload. |
| valueOf() | Integer.valueOf("42") |
String/int โ Integer | Caches [-128, 127] โ affects ==. |
| toString() | Integer.toString(42) |
int โ String (static) | Radix overload available. |
| toBinaryString() / toHexString() / toOctalString() |
Integer.toHexString(255)
|
int โ string in base | No prefix. For negatives: 2's complement. |
| MAX_VALUE / MIN_VALUE | Integer.MAX_VALUE |
Int bounds (FIELDS) | +1 wraps to MIN. |
| compare() | Integer.compare(a, b) |
Safe lexicographic compare | Avoid a-b (overflow). |
| sum() / max() / min() | Integer.sum(3, 4) |
Method-reference helpers | Useful with reduce / Collectors. |
| bitCount() | Integer.bitCount(7) |
Population count of 1-bits | Useful for bitmask problems. |
| numberOfLeadingZeros() NEW |
Integer.numberOfLeadingZeros(n)
|
Leading 0-bits | Useful for logโ / size class calc. |
| numberOfTrailingZeros() NEW |
Integer.numberOfTrailingZeros(n)
|
Trailing 0-bits | Position of lowest set bit. |
| highestOneBit() / lowestOneBit() NEW |
Integer.highestOneBit(n)
|
Isolate hi/lo set bit | Returns power of two. |
| reverse() / reverseBytes() NEW | Integer.reverse(n) |
Reverse bits / byte order | Useful in encoding/IO. |
| signum() NEW | Integer.signum(n) |
โ1 / 0 / 1 | Branchless sign. |
| parseUnsignedInt() / toUnsignedLong() NEW |
Integer.parseUnsignedInt("4294967295")
|
Unsigned arithmetic helpers | Java 8+ unsigned operations. |
| Double.parseDouble() |
Double.parseDouble("3.14")
|
String โ double | Accepts NaN, Infinity strings. |
| Double.isNaN() | Double.isNaN(x) |
NaN check | Don't use ==. NaN != NaN. |
| Double.isInfinite() / isFinite() NEW | Double.isFinite(x) |
ยฑโ / finite check | isFinite is Java 8+. |
| Boolean.parseBoolean() |
Boolean.parseBoolean("true")
|
String โ boolean | Only "true" (case-insens) โ true. |
| Character.isLetter() / isDigit() / isLetterOrDigit() / isWhitespace() |
Character.isDigit('5')
|
Char predicates | Unicode-aware. |
| Character.toUpperCase() / toLowerCase() |
Character.toUpperCase('a')
|
Char case conversion | For Strings use String methods. |
| Character.getNumericValue() |
Character.getNumericValue('A')
|
Numeric value (e.g. 'A' โ 10) | Useful for radix conversions. |
| Character.isAlphabetic() NEW |
Character.isAlphabetic(cp)
|
Code-point alphabetic check | Broader than isLetter. |
13Stream API Methods
Lazy: intermediate ops don't execute until a terminal op runs. A stream can only be consumed ONCE.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| filter() |
stream.filter(x -> x > 0)
|
Keep matching elements | Intermediate. |
| map() |
stream.map(x -> x * 2)
|
1:1 transform | Intermediate. |
| mapToInt() / mapToLong() / mapToDouble() |
stream.mapToInt(String::length)
|
To primitive stream | Avoids boxing; enables sum() etc. |
| mapToObj() NEW |
intStream.mapToObj(Integer::toString)
|
Primitive โ object stream | Inverse of mapToInt. |
| boxed() NEW | intStream.boxed() |
Box to Stream<Integer> | Cleaner than mapToObj for plain boxing. |
| flatMap() |
stream.flatMap(Collection::stream)
|
1:N โ flatten | Intermediate. |
| distinct() | stream.distinct() |
Dedupe via equals/hash | Intermediate. May be heavy. |
| sorted() | stream.sorted() |
Natural / Comparator sort | Buffers all elements. |
| limit() / skip() | stream.limit(5) |
Truncate / drop prefix | limit short-circuits โ fine for infinite streams. |
| takeWhile() / dropWhile() NEW |
stream.takeWhile(x -> x < 10)
|
Conditional prefix (Java 9+) | Order-sensitive. |
| peek() |
stream.peek(System.out::println)
|
Side-effect on each (debug) | โ ๏ธ Don't rely on it in production. |
| collect() |
stream.collect(Collectors.toList())
|
Reduce into container | Terminal. |
| toList() โ | stream.toList() |
Unmodifiable list (Java 16+) | For mutable use Collectors.toList(). |
| forEach() |
stream.forEach(System.out::println)
|
Action per element | Order undefined in parallel. |
| reduce() |
stream.reduce(0, Integer::sum)
|
Fold to single value | Identity arg โ no Optional. |
| count() | stream.count() |
Element count | Terminal. Returns long. |
| findFirst() / findAny() | stream.findFirst() |
Optional first / any | Short-circuit. |
| anyMatch() / allMatch() / noneMatch() |
stream.anyMatch(x -> x > 0)
|
Quantifier predicates | Short-circuit. |
| min() / max() |
stream.min(Comparator.naturalOrder())
|
Optional min / max | Empty stream โ empty Optional. |
| Stream.of() | Stream.of(1, 2, 3) |
Stream from values |
For arrays use Arrays.stream().
|
| Stream.empty() / generate() / iterate() NEW |
Stream.iterate(1, x -> x*2)
|
Empty/infinite streams | Combine with limit(). |
| Stream.concat() NEW | Stream.concat(s1, s2) |
Lazy concatenation | Use flatMap for many streams. |
| IntStream.range() / rangeClosed() |
IntStream.range(0, 10)
|
[from, to) / [from, to] | Useful for index loops. |
| Collectors.toList() / toSet() |
.collect(Collectors.toSet())
|
Standard collectors | Mutable result. |
| Collectors.toMap() NEW |
.collect(Collectors.toMap(k, v))
|
Build a Map | Throws on duplicate keys โ pass merge fn. |
| Collectors.groupingBy() โ |
.collect(Collectors.groupingBy(fn))
|
Map<K, List<V>> | Downstream collector overload available. |
| Collectors.partitioningBy() NEW |
.collect(Collectors.partitioningBy(p))
|
Map<Boolean, List<V>> | Two-bucket variant of groupingBy. |
| Collectors.counting() NEW |
groupingBy(fn, Collectors.counting())
|
Count per group | Returns Map<K, Long>. |
| Collectors.joining() โ |
.collect(Collectors.joining(", "))
|
Concat strings | Overloads: joining(), (delim), (delim, prefix, suffix). |
| Collectors.summarizingInt() NEW |
.collect(Collectors.summarizingInt(fn))
|
min/max/avg/sum/count at once | Returns IntSummaryStatistics. |
| Collectors.mapping() NEW |
groupingBy(k, mapping(v, toList()))
|
Adapt elements before downstream | Common with groupingBy. |
| Collectors.reducing() NEW |
.collect(Collectors.reducing(0, Integer::sum))
|
Fold collector | Use as a downstream collector too. |
| Stream.mapMulti() NEW |
stream.mapMulti((x, c) -> โฆ)
|
Push 0..N items (Java 16+) | Often faster than flatMap for short fan-out. |
14Optional Methods
A holder that may be empty.
Don't call get() without checking
โ use map/orElse/ifPresent.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| Optional.of() | Optional.of(value) |
Non-null required | NPE if null. |
| Optional.ofNullable() |
Optional.ofNullable(value)
|
Null-safe wrap | Empty if null. |
| Optional.empty() | Optional.empty() |
The empty Optional | Same singleton. |
| isPresent() / isEmpty() | opt.isPresent() |
Presence check | isEmpty() is Java 11+. |
| get() | opt.get() |
Unwrap (throws if empty) | โ ๏ธ Defeats the point โ prefer orElse. |
| orElse() | opt.orElse("default") |
Value or fallback | Default ALWAYS evaluated. |
| orElseGet() |
opt.orElseGet(() -> compute())
|
Value or lazy supplier | Use for expensive defaults. |
| orElseThrow() | opt.orElseThrow() |
Value or throw | Overload for custom exception. |
| ifPresent() |
opt.ifPresent(System.out::println)
|
Conditional action | Cleaner than isPresent + get. |
| ifPresentOrElse() NEW |
opt.ifPresentOrElse(action, emptyAction)
|
Two-branch action (Java 9+) | Replaces if/else on isPresent. |
| map() |
opt.map(String::toUpperCase)
|
Transform if present | Empty stays empty. |
| flatMap() |
opt.flatMap(this::findUser)
|
Unwrap nested Optional | When transform returns Optional. |
| filter() |
opt.filter(x -> x > 0)
|
Empty if predicate fails | Like Stream.filter for one element. |
| or() NEW |
opt.or(() -> otherOpt)
|
Fallback Optional (Java 9+) | Chain alternative sources. |
| stream() NEW | opt.stream() |
0/1-element Stream (Java 9+) | Useful in flatMap pipelines. |
15Object & Objects Methods
Every class inherits from Object.
Always override equals() and
hashCode() together.
| Method | Syntax | Description | Notes |
|---|---|---|---|
| toString() | obj.toString() |
String representation |
Default Class@hex. Override.
|
| equals() | obj.equals(other) |
Logical equality | Default = reference equality. |
| hashCode() | obj.hashCode() |
Hash for buckets | Must be consistent with equals(). |
| getClass() | obj.getClass() |
Runtime class |
Often instanceof is better.
|
| clone() | obj.clone() |
Shallow copy | Class must implement Cloneable. |
| notify() / notifyAll() / wait() | obj.wait() |
Intrinsic monitor signaling | Must hold monitor. Use j.u.c.Condition for new code. |
| Objects.equals() | Objects.equals(a, b) |
Null-safe equality | No NPE if a is null. |
| Objects.hash() | Objects.hash(a, b, c) |
Combine fields | For hashCode() overrides. |
| Objects.requireNonNull() |
Objects.requireNonNull(arg, "arg")
|
Validate non-null | Throws NPE with message. |
| Objects.requireNonNullElse() NEW |
Objects.requireNonNullElse(x, def)
|
Non-null or default (Java 9+) | Like Optional.orElse. |
| Objects.requireNonNullElseGet() NEW |
requireNonNullElseGet(x, ()->def)
|
Lazy default (Java 9+) | Like Optional.orElseGet. |
| Objects.isNull() / nonNull() | Objects.nonNull(obj) |
Predicate references |
filter(Objects::nonNull).
|
| Objects.toString() NEW |
Objects.toString(obj, "?")
|
Null-safe toString | Returns default if null. |
| Objects.compare() NEW |
Objects.compare(a, b, comp)
|
Null-safe compare | Both null โ 0. |
| Objects.checkIndex() NEW |
Objects.checkIndex(i, length)
|
Bounds check (Java 9+) | Throws IOOB if invalid. |
16Comparable & Comparator
Comparable = natural order in the class.
Comparator = external strategy. Chain with
thenComparing().
| Method | Syntax | Description | Notes |
|---|---|---|---|
| compareTo() | a.compareTo(b) |
Natural order <0 / 0 / >0 | Used by sort and TreeSet. |
| Comparator.naturalOrder() |
Comparator.naturalOrder()
|
Ascending natural | Equivalent to passing null to sort. |
| Comparator.reverseOrder() |
Comparator.reverseOrder()
|
Descending natural | Quick negation. |
| Comparator.comparing() |
Comparator.comparing(Person::getName)
|
By extracted key | Most common factory. |
| Comparator.comparingInt() / comparingLong() / comparingDouble() NEW |
Comparator.comparingInt(String::length)
|
Primitive-keyed compare | No boxing overhead. |
| thenComparing() |
comp.thenComparing(Person::getAge)
|
Secondary key | Chain N levels of tie-break. |
| thenComparingInt() NEW |
comp.thenComparingInt(Person::getAge)
|
Primitive secondary | Avoids boxing. |
| reversed() | comp.reversed() |
Negate the comparator | Pairs with comparing(). |
| nullsFirst() / nullsLast() |
Comparator.nullsLast(naturalOrder())
|
Null-handling wrapper | Without it, nulls cause NPE during sort. |