- Collections Framework Overview (Oracle)
- Outline of the Collections Framework (Oracle)
- Java Collections - Introduction (Jakob Jenkov)
- Java HashMap Load Factor (Baeldung)
- Guava: New Collection Types
Source: https://techvidvan.com/tutorials/java-collection-framework/
- enables for-each loop
Mapdoesn't extendIterable(we iterate overmap.entrySet())- methods
iterator()forEach(Consumer)spliterator()
- allow the caller to remove elements from the underlying collection during the iteration
- methods
hasNext()next()remove()forEachRemaining()- modern approach how to iterate the iterator
- copy constructors convention
- use them for conversion (for example
SettoList)
- use them for conversion (for example
- view collections - backed by the real collection
- unmodifiable, synchronized, subList, subSet, entrySet
- methods
removeIf(Predicate)retainAll(Collection)
- sequence, access by index
- methods
List.of(),List.copyOf()- unmodifiable, cannot contain null
ArrayList- dynamic array, automatic capacity handlingLinkedList- doubly-linked, implementsDeque- see LinkedList methods (Javadoc)
- unique elements, may or may not be ordered
- methods
Set.of(),Set.copyOf()- unmodifiable, cannot contain null
- implemented by
HashMap- see below LinkedHashSet- preserves insertion order (combination of hash table and linked list)
- analogue to
SortedMap - methods
first(), last()headSet(E to), tailSet(E from)
NavigableSetinterface - analogue toNavigableMap- methods
pollFirst(), pollLast()lower(E), higher(E)- return closest element lower (higher) than the given keyfloor(E), ceiling(E)- return closest element lower (higher) or equal than the given key
TreeSet- implemented by
TreeMap- see below
- implemented by
- methods
EnumSet- for use with enum types, memory effective
- copy constructors convention
- doesn't extend from
Collection - use mutable object as keys with great caution
- methods
keySet(), entrySet(), values()getOrDefault(key, default)replace(key, newValue)- iff the key is already mapped to a value (notnull)putIfAbsent(key, value)forEach(BiConsumer)compute(key, BiFunction<K,V>)- lambda to operate on the given key and valuecomputeIfAbsent(key, Function<K>)- same as ^^ but called iff key is absentcomputeIfPresent(key, BiFunction<K,V>)- same as ^^ but called iff key is presentmerge(key, newValue, BiFunction<oldVal, newVal>)- lambda is called when the key is present, else newValue is inserted
- default choice, fastest
- get/put
O(1), iteration speed depends oncapacity(i.e. the number of buckets) nullkey is allowedLinkedHashMap- preserves insertion order (or access-order, good for LRU caches)
- maintains a doubly-linked list running through all of its entries
- sorted by natural order, or by provided
Comparator - uses compareTo, not equals
- methods
firstKey(), lastKey()headMap(K to), tailMap(K from)
NavigableMapinterface - extendsSortedMapwith navigation methods returning the closest matches- methods
pollFirstEntry(), pollLastEntry()lowerEntry(K), higherEntry(K)- return closest entry lower (higher) than the given keyfloorEntry(K), ceilingEntry(K)- return closest entry lower (higher) or equal than the given key
TreeMap- natural ordering, keys must implement
Comparable, - self-balanced (Red-Black tree)
- add/remove/contains
O(log n)
- natural ordering, keys must implement
- methods
WeakHashMap- stores weak references (eligible for gc)EnumMap- for use with enum types, memory effectiveProperties- persistent set of properties, methods for loading and storing
- capacity is the number of buckets (array size)
- HashMap init capacity is
16, default load factor is0.75 - rehashing - when the current capacity * load factor > number of elements
- for HashMap, first rehashing at
(16 * 0.75) + 1 = 13entries
- for HashMap, first rehashing at
- small load factor means faster lookups (due to fewer collisions) but slower iterations and bigger memory cost (both due to a big backing array)
- collision handling
- prior to Java 8 - linked lists
- since Java 8 - balanced trees (red-black) if more than 8 collisions on the same index
- methods
add(E), offer(E)-addthrows exception if the queue is full,offerreturnsfalseremove(), poll()-removethrows exception if the queue is empty,pollreturnsnullelement(), peek()-elementthrows exception if the queue is empty,peekreturnsnull
- sorted by natural order, or by provided
Comparator- null not permitted
- unbounded
- head points to the least element
- heap based implementation
- double-ended queue (pronounced "deck") - insertion and removal at both ends
- implemented by
LinkedListandArrayDeque ArrayDeque- resizable-array implementation of the Deque interface
- unbounded
- likely to be faster than
Stackwhen used as a stack, and faster thanLinkedListwhen used as a queue
- extends from deprecated
Vector - use
ArrayDequeorLinkedListwhich both implementsDequeaddFirst(E)- pushremoveFirst()- pollgetFirst()- peek
sort(col)binarySearch(col, el)- collection must be sortedreverse(col)shuffle(col)min(col),max(col)emptyXXX()singletonXXX()synchronizedXXX()unmodifiableXXX()frequency(col, el)rotate(col, distance)swap(list, i, j)
