Post

🍡 Core Collection Interfaces Cheatsheet: Foundations of Java Collections Framework

🍡 Core Collection Interfaces Cheatsheet: Foundations of Java Collections Framework

Alt Text

Java Collection Framework – Overview Table

ClassInterface(s) ImplementedAlso Implements / ExtendsOrderingDuplicatesNull AllowedThread SafeFail‑Fast IteratorPerformance (Avg)Legacy/ModernTypical Use Case
ArrayList πŸ”΄ListRandomAccess, Cloneable, SerializableInsertionβœ… Yesβœ… Multiple nulls❌ Noβœ… YesO(1) get, O(n) removeModernDynamic array, fast random access
LinkedList 🟒List, Deque, QueueCloneable, SerializableInsertionβœ… Yesβœ… Yes❌ Noβœ… YesO(1) add/remove at endsModernFrequent insertion/deletion or queue
Vector πŸ”΄πŸ‘΄πŸ”ListRandomAccess, Cloneable, SerializableInsertionβœ… Yesβœ… Yesβœ… Yesβœ… YesO(1) synchronizedLegacyThread-safe list (historical use)
Stack πŸ”΄πŸ‘΄πŸ”List (via Vector)extends VectorLIFOβœ… Yesβœ… Yesβœ… Yesβœ… YesO(1) push/popLegacyClassic stack operations
CopyOnWriteArrayList πŸ”΄πŸ”ListCloneable, SerializableInsertionβœ… Yesβœ… Yesβœ… Yes❌ (snapshot)O(n) writes, O(1) readModern (Concurrent)Thread-safe mostly-read list
HashSet πŸ”΅SetCloneable, SerializableUnordered❌ Noβœ… One null❌ Noβœ… YesO(1) operationsModernUnique items, high performance
LinkedHashSet πŸ”΅πŸŸ’Setextends HashSet, SerializableInsertion❌ Noβœ… Yes❌ Noβœ… YesO(1) operationsModernMaintains insertion order
TreeSet 🟣NavigableSet, SortedSetCloneable, SerializableSorted❌ No❌ No❌ Noβœ… YesO(log n) operationsModernSorted set, ordered operations
CopyOnWriteArraySet πŸ”΄πŸ”SetCloneable, SerializableInsertion❌ Noβœ… Yesβœ… Yes❌ (snapshot)O(n) writes, O(1) readModern (Concurrent)Read-heavy thread-safe set
ConcurrentSkipListSet πŸŸ£πŸ”NavigableSet, SortedSet, SetCloneable, SerializableSorted❌ No❌ Noβœ… Yes❌ (weakly consistent)O(log n) concurrent opsModern (Concurrent)Highly concurrent sorted set
PriorityQueue 🟑QueueSerializablePriority (custom/natural)βœ… Yesβœ… Yes❌ Noβœ… YesO(log n) insertionModernPriority-based ordering
ArrayDeque πŸ”΄DequeCloneable, SerializableInsertionβœ… Yes❌ No❌ Noβœ… YesO(1) at endsModernEfficient stack/queue without blocking
LinkedBlockingDeque πŸŸ’πŸ”BlockingDeque, Deque, QueueSerializableFIFO or LIFOβœ… Yesβœ… Yesβœ… Yes❌ (weakly consistent)O(1) operationsModern (Concurrent)Thread-safe double-ended queue
LinkedBlockingQueue πŸŸ’πŸ”BlockingQueue, QueueSerializableFIFOβœ… Yesβœ… Yesβœ… Yes❌O(1) operationsModern (Concurrent)Producer-consumer queue
ArrayBlockingQueue πŸ”΄πŸ”BlockingQueue, QueueSerializableFIFO (bounded)βœ… Yes❌ Noβœ… Yes❌O(1) operationsModern (Concurrent)Fixed-size blocking queue
PriorityBlockingQueue πŸŸ‘πŸ”BlockingQueue, QueueSerializablePriorityβœ… Yesβœ… Yesβœ… Yes❌O(log n) insertionModern (Concurrent)Concurrent priority queue
DelayQueue πŸŸ‘πŸ”BlockingQueue, QueueSerializableDelay-orderedβœ… Yes❌ Noβœ… Yes❌O(log n) operationsModern (Concurrent)Scheduled task queue
SynchronousQueue βšͺπŸ”BlockingQueue, QueueSerializableNone (hand-off only)❌ No❌ Noβœ… Yes❌O(1)Modern (Concurrent)Thread rendezvous queue
LinkedTransferQueue πŸŸ’πŸ”TransferQueue, BlockingQueue, QueueSerializableFIFOβœ… Yesβœ… Yesβœ… Yes❌O(1) operationsModern (Concurrent)High-throughput producer-consumer handoff
HashMap πŸ”΅MapCloneable, SerializableUnordered❌ Keysβœ… one null key, multiple null values❌ Noβœ… YesO(1) operationsModernGeneral-purpose map
LinkedHashMap πŸŸ’πŸ”΅Mapextends HashMap, SerializableInsertion❌ Noβœ… Yes❌ Noβœ… YesO(1) operationsModernMaintains insertion order
TreeMap 🟣NavigableMap, SortedMap, MapCloneable, SerializableSorted❌ No❌ No❌ Noβœ… YesO(log n) operationsModernSorted key-value map
ConcurrentHashMap πŸ”΅πŸ”ConcurrentMap, MapSerializable, CloneableUnordered❌ No❌ Noβœ… Yes❌ (weakly consistent)O(1) concurrent accessModern (Concurrent)High-performance concurrent map
ConcurrentSkipListMap πŸŸ£πŸ”ConcurrentNavigableMap, MapSerializable, CloneableSorted❌ No❌ Noβœ… Yes❌ (weakly consistent)O(log n) concurrent sorted opsModern (Concurrent)Concurrent sorted map
WeakHashMap πŸ”΅MapSerializable, CloneableUnordered (GC-based)❌ Noβœ… Yes❌ Noβœ… YesO(1) (GC-sensitive)ModernAuto-removable keys on weak reachability
IdentityHashMap πŸ”΅MapSerializable, CloneableUnordered❌ Noβœ… Yes❌ Noβœ… YesO(1) operationsModernReference equality-based map
EnumMap πŸ”΄MapSerializable, CloneableEnum key order❌ No❌ null keys❌ Noβœ… YesO(1) operationsModernEfficient enum-key-based map
Hashtable πŸ”΅πŸ‘΄πŸ”MapCloneable, SerializableUnordered❌ No❌ Noβœ… Yesβœ… YesO(1) synchronizedLegacyLegacy thread-safe map
Dictionary πŸ‘΄ (abstract)none (abstract legacy)β€”Unordered❌ No❌ No❌ Noβ€”VariesLegacyPre‐Map abstract key/value class
πŸ”΄Array – 🟒Linked List – 🟣Tree – πŸ”΅Hash Table – 🟑Binary Heap – πŸ”Thread-safe – πŸ‘΄Legacy

Java Collection Framework β€” Complete Method Reference


Collection Interface

Method NameArgumentsReturn TypeDescriptionExample
add_E e_ (required)booleanAdds element to the collectioncollection.add("item");
addAll_Collection<? extends E> c_ (required)booleanAdds all elements from another collectioncollection.addAll(otherCollection);
clearΒ voidRemoves all elementscollection.clear();
contains_Object o_ (required)booleanChecks if collection contains the elementcollection.contains("item");
containsAll_Collection<?> c_ (required)booleanChecks if collection contains all elements in ccollection.containsAll(otherCollection);
equals_Object o_ (required)booleanChecks equality with another objectcollection.equals(anotherCollection);
hashCodeΒ intReturns hash codecollection.hashCode();
isEmptyΒ booleanChecks if collection is emptycollection.isEmpty();
iteratorΒ Iterator<E>Returns an iterator over elementsIterator<E> it = collection.iterator();
parallelStreamΒ Stream<E>Returns a parallel Stream of elementscollection.parallelStream().forEach(...);
remove_Object o_ (required)booleanRemoves a single instance of specified elementcollection.remove("item");
removeAll_Collection<?> c_ (required)booleanRemoves all elements contained in collection ccollection.removeAll(otherCollection);
removeIf_Predicate<? super E> filter_ (required)booleanRemoves all elements matching predicatecollection.removeIf(e -> e.isEmpty());
retainAll_Collection<?> c_ (required)booleanRetains only elements contained in collection ccollection.retainAll(otherCollection);
sizeΒ intReturns number of elementsint size = collection.size();
streamΒ Stream<E>Returns a sequential Stream of elementscollection.stream().filter(...);
toArrayΒ Object[]Returns an array of all elementsObject[] arr = collection.toArray();
toArray_T[] a_ (required)T[]Returns array containing elements of runtime typeString[] arr = collection.toArray(new String[0]);
forEach_Consumer<? super E> action_ (required)voidPerforms given action for each elementcollection.forEach(System.out::println);
spliteratorΒ Spliterator<E>Returns a Spliterator over elementsSpliterator<E> spliterator = collection.spliterator();

List<E> Interface – Full Cheatsheet

Method NameArgumentsReturn TypeDescriptionAvg. Time ⏱Java VersionExample
addβ˜…β˜…β˜…int index, E element (required)voidInserts element at specified positionO(n)1.2list.add(1, "item");
addβ˜…β˜…β˜…E element (required)booleanAdds element to end of listO(1) amort.1.2list.add("item");
addAllβ˜…β˜…int index, Collection<? extends E> cbooleanInserts all elements at specified positionO(n + m)1.2list.addAll(1, collection);
addAllβ˜…β˜…β˜…Collection<? extends E> cbooleanAdds all elements to end of listO(m)1.2list.addAll(collection);
clearβ˜…β˜…β˜…Β voidRemoves all elementsO(n)1.2list.clear();
containsβ˜…β˜…β˜…Object o (required)booleanChecks if element is presentO(n)1.2list.contains("item");
containsAllβ˜…β˜…Collection<?> c (required)booleanChecks if all elements are presentO(nΓ—m)1.2list.containsAll(collection);
equalsβ˜…β˜…Object o (required)booleanCompares equalityO(n)1.2list.equals(otherList);
getβ˜…β˜…β˜…int index (required)EReturns element at positionO(1)1.2E element = list.get(1);
indexOfβ˜…β˜…β˜…Object o (required)intReturns index of first occurrenceO(n)1.2int i = list.indexOf("item");
isEmptyβ˜…β˜…β˜…Β booleanChecks if list is emptyO(1)1.2list.isEmpty();
iteratorβ˜…β˜…Β Iterator<E>Returns iteratorO(1)1.2Iterator<E> it = list.iterator();
lastIndexOfβ˜…β˜…Object o (required)intReturns index of last occurrenceO(n)1.2int i = list.lastIndexOf("item");
listIteratorβ˜…β˜…Β ListIterator<E>Returns list iteratorO(1)1.2ListIterator<E> it = list.listIterator();
listIteratorβ˜…β˜…int index (required)ListIterator<E>Returns list iterator starting at indexO(1)1.2ListIterator<E> it = list.listIterator(1);
removeβ˜…β˜…β˜…int index (required)ERemoves element at indexO(n)1.2E removed = list.remove(1);
removeβ˜…β˜…β˜…Object o (required)booleanRemoves first occurrence of elementO(n)1.2list.remove("item");
removeAllβ˜…β˜…Collection<?> c (required)booleanRemoves all matching elementsO(nΓ—m)1.2list.removeAll(collection);
retainAllβ˜…β˜…Collection<?> c (required)booleanRetains only elements present in collectionO(nΓ—m)1.2list.retainAll(collection);
setβ˜…β˜…β˜…int index, E element (required)EReplaces element at indexO(1)1.2list.set(1, "newItem");
sizeβ˜…β˜…β˜…Β intReturns size of listO(1)1.2int size = list.size();
subListβ˜…β˜…int fromIndex, int toIndex (required)List<E>Returns sublist viewO(1)ΒΉ1.2List<E> sub = list.subList(1, 3);
toArrayβ˜…β˜…β˜…Β Object[]Returns array of elementsO(n)1.2Object[] arr = list.toArray();
toArrayβ˜…β˜…β˜…T[] a (required)<T[]>Returns array in provided array typeO(n)1.2String[] arr = list.toArray(new String[0]);

πŸ—οΈ Static Methods in List Interface

Method NameArgumentsReturn TypeDescriptionAvg. Time ⏱Java VersionExample
ofβ˜…β˜…β˜…E... elements (required)List<E>Immutable list of elementsO(n)9+List.of("a", "b")
copyOfβ˜…β˜…Collection<? extends E> c (required)List<E>Immutable copy of collectionO(n)9+List.copyOf(myList)

πŸ› οΈ Utility Methods from Collections and Arrays

Method NameArgumentsReturn TypeDescriptionAvg. Time ⏱Java VersionExample
Collections.unmodifiableListβ˜…β˜…List<? extends T> list (required)List<T>Read-only wrapper over original listO(1)1.2Collections.unmodifiableList(myList)
Collections.singletonListβ˜…β˜…T item (required)List<T>Immutable list with a single elementO(1)1.2Collections.singletonList("a")
Arrays.asListβ˜…β˜…β˜…T... a (required)List<T>Fixed-size list backed by an arrayO(1)1.2Arrays.asList("x", "y")

Queue<E> Interface – Full Cheatsheet

Method NameArgumentsReturn TypeDescriptionAvg. Time ⏱Java VersionExample
addβ˜…β˜…β˜…E e (required)booleanInserts element or throws exceptionO(1)1.5queue.add("item");
offerβ˜…β˜…β˜…E e (required)booleanInserts element or returns false if fullO(1)1.5queue.offer("item");
pollβ˜…β˜…β˜…Β ERetrieves and removes head, or null if emptyO(1)1.5E e = queue.poll();
removeβ˜…β˜…Β ERetrieves and removes head, throws if emptyO(1)1.5E e = queue.remove();
peekβ˜…β˜…β˜…Β ERetrieves head or null if emptyO(1)1.5E e = queue.peek();
elementβ˜…β˜…Β ERetrieves head or throws if emptyO(1)1.5E e = queue.element();

πŸ—οΈ Static Methods in Collections (Queue Utilities)

Method NameArgumentsReturn TypeDescriptionAvg. Time ⏱Java VersionExample
Collections.asLifoQueueβ˜…Deque<T> deque (required)Queue<T>Returns a LIFO view of a dequeO(1)1.6Queue<T> lifo = Collections.asLifoQueue(deque);
Collections.unmodifiableQueueβ˜…Queue<? extends T> queue (required)Queue<T>Returns an unmodifiable view of a queueO(1)1.5Queue<T> unmod = Collections.unmodifiableQueue(queue);

πŸ› οΈ Static Factory Methods (Java 9+)

Method NameArgumentsReturn TypeDescriptionAvg. Time ⏱Java VersionExample
Queue.ofβ˜…β˜…β˜…E... elements (required)Queue<E>Creates an unmodifiable queue with elementsO(n)9+Queue<String> q = Queue.of("A", "B");
Queue.copyOfβ˜…β˜…Collection<? extends E> coll (required)Queue<E>Creates an unmodifiable queue from collectionO(n)9+Queue<String> q = Queue.copyOf(list);

Deque Interface (extends Queue)

Method NameArgumentsReturn TypeDescriptionExample
addFirst_E e_ (required)voidInserts at frontdeque.addFirst("item");
addLast_E e_ (required)voidInserts at enddeque.addLast("item");
offerFirst_E e_ (required)booleanInserts at front or false if fulldeque.offerFirst("item");
offerLast_E e_ (required)booleanInserts at end or false if fulldeque.offerLast("item");
pollFirstΒ ERetrieves and removes first or null if emptyE e = deque.pollFirst();
pollLastΒ ERetrieves and removes last or null if emptyE e = deque.pollLast();
peekFirstΒ ERetrieves first or null if emptyE e = deque.peekFirst();
peekLastΒ ERetrieves last or null if emptyE e = deque.peekLast();
removeFirstΒ ERetrieves and removes first, throws if emptyE e = deque.removeFirst();
removeLastΒ ERetrieves and removes last, throws if emptyE e = deque.removeLast();
getFirstΒ ERetrieves first, throws if emptyE e = deque.getFirst();
getLastΒ ERetrieves last, throws if emptyE e = deque.getLast();
removeFirstOccurrence_Object o_ (required)booleanRemoves first occurrence of objectdeque.removeFirstOccurrence(obj);
removeLastOccurrence_Object o_ (required)booleanRemoves last occurrence of objectdeque.removeLastOccurrence(obj);

Map<K,V> Interface

Method NameArgumentsReturn TypeDescriptionExample
clearΒ voidRemoves all mappingsmap.clear();
compute_K key_, _BiFunction<? super K, ? super V, ? extends V> remappingFunction_ (required)VComputes new valuemap.compute("key", (k,v) -> v == null ? 1 : v + 1);
computeIfAbsent_K key_, _Function<? super K, ? extends V> mappingFunction_ (required)VComputes value if absentmap.computeIfAbsent("key", k -> 1);
computeIfPresent_K key_, _BiFunction<? super K, ? super V, ? extends V> remappingFunction_ (required)VComputes new value if presentmap.computeIfPresent("key", (k,v) -> v + 1);
containsKey_Object key_ (required)booleanChecks if map contains keymap.containsKey("key");
containsValue_Object value_ (required)booleanChecks if map contains valuemap.containsValue("value");
entrySetΒ Set<Map.Entry<K,V>>Returns a set view of mappingsSet<Map.Entry<K,V>> entries = map.entrySet();
equals_Object o_ (required)booleanChecks equalitymap.equals(otherMap);
forEach_BiConsumer<? super K, ? super V> action_ (required)voidPerforms action for each mappingmap.forEach((k,v) -> System.out.println(k + v));
get_Object key_ (required)VReturns value for keyV val = map.get("key");
getOrDefault_Object key_, _V defaultValue_ (required)VReturns value or default if absentV val = map.getOrDefault("key", defaultVal);
isEmptyΒ booleanChecks if map is emptymap.isEmpty();
keySetΒ Set<K>Returns set of keysSet<K> keys = map.keySet();
merge_K key_, _V value_, _BiFunction<? super V, ? super V, ? extends V> remappingFunction_ (required)VMerges valuemap.merge("key", "value", (v1, v2) -> v1 + v2);
put_K key_, _V value_ (required)VAdds or replaces mappingmap.put("key", "value");
putAll_Map<? extends K, ? extends V> m_ (required)voidCopies all mappingsmap.putAll(otherMap);
remove_Object key_ (required)VRemoves mappingmap.remove("key");
replace_K key_, _V value_ (required)VReplaces value for keymap.replace("key", "newValue");
replaceAll_BiFunction<? super K, ? super V, ? extends V> function_ (required)voidReplaces all values using functionmap.replaceAll((k, v) -> v.toUpperCase());
sizeΒ intReturns number of mappingsint size = map.size();
valuesΒ Collection<V>Returns collection of valuesCollection<V> values = map.values();

SortedMap<K,V> Interface (extends Map<K,V>)

Method NameArgumentsReturn TypeDescriptionExample
comparatorΒ Comparator<? super K>Returns comparator or null if naturalComparator<K> c = sortedMap.comparator();
subMap_K fromKey_, _K toKey_ (required)SortedMap<K,V>Returns view between keysSortedMap<K,V> sm = sortedMap.subMap(fromKey, toKey);
headMap_K toKey_ (required)SortedMap<K,V>Returns view of keys less than toKeySortedMap<K,V> hm = sortedMap.headMap(toKey);
tailMap_K fromKey_ (required)SortedMap<K,V>Returns view of keys greater or equalSortedMap<K,V> tm = sortedMap.tailMap(fromKey);
firstKeyΒ KReturns first (lowest) keyK first = sortedMap.firstKey();
lastKeyΒ KReturns last (highest) keyK last = sortedMap.lastKey();

Method NameArgumentsReturn TypeDescriptionExample
ceilingEntry_K key_ (required)Map.Entry<K,V>Least entry with key β‰₯ given keyMap.Entry<K,V> e = navMap.ceilingEntry(key);
ceilingKey_K key_ (required)KLeast key β‰₯ given keyK k = navMap.ceilingKey(key);
descendingKeySetΒ NavigableSet<K>Returns reverse order key setNavigableSet<K> ks = navMap.descendingKeySet();
descendingMapΒ NavigableMap<K,V>Returns reverse order mapNavigableMap<K,V> dm = navMap.descendingMap();
floorEntry_K key_ (required)Map.Entry<K,V>Greatest entry with key ≀ given keyMap.Entry<K,V> e = navMap.floorEntry(key);
floorKey_K key_ (required)KGreatest key ≀ given keyK k = navMap.floorKey(key);
higherEntry_K key_ (required)Map.Entry<K,V>Least entry with key > given keyMap.Entry<K,V> e = navMap.higherEntry(key);
higherKey_K key_ (required)KLeast key > given keyK k = navMap.higherKey(key);
headMap_K toKey_, _boolean inclusive_ (required)NavigableMap<K,V>Returns view of keys less than (inclusive)NavigableMap<K,V> hm = navMap.headMap(toKey, true);
lastEntryΒ Map.Entry<K,V>Returns last entryMap.Entry<K,V> e = navMap.lastEntry();
lowerEntry_K key_ (required)Map.Entry<K,V>Greatest entry with key < given keyMap.Entry<K,V> e = navMap.lowerEntry(key);
lowerKey_K key_ (required)KGreatest key < given keyK k = navMap.lowerKey(key);
pollFirstEntryΒ Map.Entry<K,V>Removes and returns first entryMap.Entry<K,V> e = navMap.pollFirstEntry();
pollLastEntryΒ Map.Entry<K,V>Removes and returns last entryMap.Entry<K,V> e = navMap.pollLastEntry();
subMap_K fromKey_, _boolean fromInclusive_, _K toKey_, _boolean toInclusive_ (required)NavigableMap<K,V>Returns view between keysNavigableMap<K,V> sm = navMap.subMap(fromKey, true, toKey, false);
tailMap_K fromKey_, _boolean inclusive_ (required)NavigableMap<K,V>Returns view of keys β‰₯ given keyNavigableMap<K,V> tm = navMap.tailMap(fromKey, true);

SortedSet Interface

Method NameArgumentsReturn TypeDescriptionExample
comparatorΒ Comparator<? super E>Returns the comparator used for sorting, or null if natural orderComparator c = sortedSet.comparator();
firstΒ EReturns the first (lowest) elementE first = sortedSet.first();
lastΒ EReturns the last (highest) elementE last = sortedSet.last();
headSet_E toElement_ (required)SortedSet<E>Elements strictly less than toElementSortedSet<E> head = sortedSet.headSet(e);
tailSet_E fromElement_ (required)SortedSet<E>Elements greater than or equal to fromElementSortedSet<E> tail = sortedSet.tailSet(e);
subSet_E fromElement_, _E toElement_ (required)SortedSet<E>Elements in range from (inclusive) to to (exclusive)SortedSet<E> sub = sortedSet.subSet(from, to);

Method NameArgumentsReturn TypeDescriptionExample
ceiling_E e_ (required)EReturns the least element β‰₯ e, or null if noneE c = navSet.ceiling(e);
floor_E e_ (required)EReturns the greatest element ≀ e, or null if noneE f = navSet.floor(e);
higher_E e_ (required)EReturns the least element > e, or null if noneE h = navSet.higher(e);
lower_E e_ (required)EReturns the greatest element < e, or null if noneE l = navSet.lower(e);
pollFirstΒ ERetrieves and removes the first (lowest) element, or nullE first = navSet.pollFirst();
pollLastΒ ERetrieves and removes the last (highest) element, or nullE last = navSet.pollLast();
descendingSetΒ NavigableSet<E>Returns a reverse-order view of the setNavigableSet<E> rev = navSet.descendingSet();
descendingIteratorΒ Iterator<E>Returns an iterator over elements in reverse orderIterator<E> it = navSet.descendingIterator();
headSet_E toElement_, _boolean inclusive_ (required)NavigableSet<E>View of elements less than (or equal) to toElementNavigableSet<E> hs = navSet.headSet(e, true);
tailSet_E fromElement_, _boolean inclusive_ (required)NavigableSet<E>View of elements greater than (or equal) to fromElementNavigableSet<E> ts = navSet.tailSet(e, true);
subSet_E fromElement_, _boolean fromInclusive_, _E toElement_, _boolean toInclusive_ (required)NavigableSet<E>View of elements between fromElement and toElementNavigableSet<E> ss = navSet.subSet(f, true, t, false);

ConcurrentMap<K,V> Interface

Method NameArgumentsReturn TypeDescriptionExample
putIfAbsent_K key_, _V value_ (required)VIf key not present, associates value with key atomically; returns previous value or null if noneV oldVal = cmap.putIfAbsent(key, value);
remove_Object key_, _Object value_ (required)booleanRemoves entry only if key is mapped to given valueboolean removed = cmap.remove(key, value);
replace_K key_, _V oldValue_, _V newValue_ (required)booleanReplaces entry for key only if currently mapped to oldValueboolean replaced = cmap.replace(key, oldVal, newVal);
replace_K key_, _V value_ (required)VReplaces entry for key only if present; returns previous value or null if noneV oldVal = cmap.replace(key, value);
computeIfAbsent_K key_, _Function<? super K,? extends V> mappingFunction_ (required)VIf key absent, computes value using mappingFunction and inserts it atomicallyV val = cmap.computeIfAbsent(key, k -> newVal);
computeIfPresent_K key_, _BiFunction<? super K,? super V,? extends V> remappingFunction_ (required)VIf key present, computes new value using remappingFunction; replaces entry atomicallyV val = cmap.computeIfPresent(key, (k,v) -> newVal);
compute_K key_, _BiFunction<? super K,? super V,? extends V> remappingFunction_ (required)VComputes new mapping for key atomicallyV val = cmap.compute(key, (k,v) -> newVal);
merge_K key_, _V value_, _BiFunction<? super V,? super V,? extends V> remappingFunction_ (required)VMerges existing value with given value using remappingFunction atomicallyV val = cmap.merge(key, value, (v1,v2) -> mergedVal);

BlockingQueue Interface

Method NameArgumentsReturn TypeDescriptionExample
putE e (required)voidInserts the element, waiting if necessary for space to become availablequeue.put(e);
takenoneERetrieves and removes the head, waiting if necessary until an element becomes availableE e = queue.take();
offerE e, long timeout, TimeUnit unit (required)booleanInserts the element, waiting up to the timeout if necessary for spaceboolean success = queue.offer(e, 1, TimeUnit.SECONDS);
polllong timeout, TimeUnit unit (required)ERetrieves and removes the head, waiting up to the timeout if necessaryE e = queue.poll(1, TimeUnit.SECONDS);
remainingCapacitynoneintReturns the number of additional elements the queue can ideally acceptint cap = queue.remainingCapacity();
drainToCollection<? super E> c (required)intRemoves all available elements and adds them to the given collectionint drained = queue.drainTo(list);
drainToCollection<? super E> c, int maxElements (required)intRemoves up to maxElements and adds them to the given collectionint drained = queue.drainTo(list, 10);

TransferQueue Interface

Method NameArgumentsReturn TypeDescriptionExample
transferE e (required)voidInserts the element and waits until it is received by a consumerqueue.transfer(e);
tryTransferE e (required)booleanAttempts to transfer the element immediately, returns false if no consumer is waitingboolean success = queue.tryTransfer(e);
tryTransferE e, long timeout, TimeUnit unit (required)booleanWaits up to timeout for a consumer to receive the element; returns false if timed outboolean success = queue.tryTransfer(e, 1, TimeUnit.SECONDS);
hasWaitingConsumernonebooleanReturns true if any consumers are waiting to receive elementsboolean waiting = queue.hasWaitingConsumer();
getWaitingConsumerCountnoneintReturns an estimate of the number of consumers waiting to receive elementsint count = queue.getWaitingConsumerCount();

ConcurrentNavigableMap<K,V> Interface

Method NameArgumentsReturn TypeDescriptionExample
subMapK fromKey, boolean fromInclusive, K toKey, boolean toInclusiveConcurrentNavigableMap<K,V>Returns a view of the portion of this map whose keys range from fromKey to toKeyConcurrentNavigableMap<K,V> view = map.subMap(k1, true, k2, false);
headMapK toKey, boolean inclusiveConcurrentNavigableMap<K,V>Returns a view of the portion of this map whose keys are less than (or equal if inclusive)ConcurrentNavigableMap<K,V> head = map.headMap(k, true);
tailMapK fromKey, boolean inclusiveConcurrentNavigableMap<K,V>Returns a view of the portion of this map whose keys are greater than (or equal if inclusive)ConcurrentNavigableMap<K,V> tail = map.tailMap(k, false);
descendingMapnoneConcurrentNavigableMap<K,V>Returns a reverse-order view of the mapConcurrentNavigableMap<K,V> rev = map.descendingMap();

Argument Types Description

➑️ _E e_:
Represents a single element of generic type E. Used in methods that add, remove, or process one element.

➑️ _Collection<? extends E> c_:
A collection containing elements of type E or its subtypes. Used when adding or manipulating multiple elements at once.

➑️ _Collection<?> c_:
A collection with unknown element type, commonly used for removal or retention operations.

➑️ _Object o_:
A general object parameter, used in equality checks or removal of a specific element.

➑️ _Predicate<? super E> filter_:
A functional interface that tests elements for a condition, used to filter or remove elements matching the predicate.

➑️ _Consumer<? super E> action_:
A functional interface representing an action to perform on each element (e.g., printing, modifying).

➑️ _T[] a_:
A generic array provided to toArray to specify the output array’s runtime type.

➑️ _int index_:
A zero-based integer index specifying position in the list for insertion, retrieval, or removal.

➑️ _int fromIndex_:
A starting index, inclusive, for sublist or subrange operations.

➑️ _int toIndex_:
An ending index, exclusive, for sublist or subrange operations.

➑️ _K key_:
The key object used in map operations such as lookup, insertion, or deletion.

➑️ _V value_:
The value associated with a key in map operations, used for insertion or replacement.

➑️ _Map<? extends K, ? extends V> m_:
A map of key-value pairs, used to bulk insert into another map.

➑️ _boolean inclusive_:
A boolean flag indicating whether boundary keys should be included (true) or excluded (false) in range operations.

➑️ _boolean fromInclusive_, _boolean toInclusive_:
Boolean flags specifying inclusiveness of the start and end keys in subrange views or operations.

➑️ _Comparator<? super E> comparator_:
A comparator defining the order of elements in sorted collections or maps.

➑️ _Iterable<? extends E> iterable_:
An iterable collection of elements used as input for bulk operations.

➑️ _Spliterator<E> spliterator_:
An object supporting parallel traversal over elements.

➑️ No arguments:
Methods with no parameters typically perform queries, clear, or return iterators over the whole collection.


Marker & Utility Interfaces

Marker & Utility Interfaces in Java – In-Depth Comparison

InterfacePackageTypePurposeDeclared MethodsCommon ImplementationsKey Notes
RandomAccessjava.utilMarker InterfaceIndicates that a List implementation supports fast random access (e.g., O(1) get/index)❌ NoneArrayList, VectorUsed by algorithms to decide if index-based traversal is efficient; not used by LinkedList
Cloneablejava.langMarker InterfaceSignals that .clone() method can be called safely; enables field-by-field memory copy❌ NoneArrayList, HashMap, DateMust override clone() manually from Object; deep vs shallow copy must be handled explicitly
Serializablejava.ioMarker InterfaceMarks a class as eligible for Java Serialization – converting object state to a byte stream❌ NoneArrayList, HashMap, StringUsed in I/O, RMI, caching; fields not marked transient will be persisted
Externalizablejava.ioFunctional InterfaceLike Serializable, but gives full control over what/how to serialize/deserializeβœ… writeExternal, readExternalRarely used directlyMust define a public no-arg constructor; improves performance & control
Comparable<T>java.langGeneric InterfaceEnables natural ordering of objects (e.g., alphabetic or numeric sorting) via compareTo()βœ… compareTo(T o)String, Integer, DateNeeded for TreeSet, TreeMap; should be consistent with equals()
Comparator<T>java.utilGeneric InterfaceEnables external/custom ordering logic without modifying the classβœ… compare(T o1, T o2)Used with Collections.sort()Can create multiple sort orders; supports chaining with thenComparing() in Java 8+

Summary by Behavior

InterfaceIs Marker?SerializationCloningSortingAccess OptimizationControl LevelUsage Context
RandomAccessβœ…βŒβŒβŒβœ… (O(1) access hint)🚫 No controlAlgorithm optimization hints
Cloneableβœ…βŒβœ…βŒβŒβš οΈ Partial controlManual clone implementation needed
Serializableβœ…βœ…βŒβŒβŒπŸš« No controlAuto save/load over stream
ExternalizableβŒβœ… (manual)βŒβŒβŒβœ… Full controlAdvanced I/O customization
ComparableβŒβŒβŒβœ…βŒβœ… Full controlNatural sorting within class
ComparatorβŒβŒβŒβœ…βŒβœ… Full controlExternal or lambda-based sorting

This post is licensed under CC BY 4.0 by the author.