Skip to content
Dev Dump

Collections Framework

The Java Collections Framework is a unified architecture of interfaces, implementations, and algorithms for working with groups of objects. Instead of writing your own data structures, you pick the right one from the framework.

benefits-collection

collection

Two separate hierarchies:

  • Collection<E> — for sequences of elements (List, Set, Queue)
  • Map<K,V> — for key-value pairs (HashMap, TreeMap)

e47c73756a31ba8b85648d4ad01c6475_MD5

2d47e4a6deba84be1dc09943b2fbc7a8_MD5

ImplementationAccessSearchInsertDeleteOrderingThread-Safe
ArrayListO(1)O(n)O(1)*O(n)InsertionNo
LinkedListO(n)O(n)O(1)O(1)InsertionNo
HashSetO(1)O(1)O(1)NoneNo
TreeSetO(log n)O(log n)O(log n)SortedNo
HashMapO(1)O(1)O(1)O(1)NoneNo
TreeMapO(log n)O(log n)O(log n)O(log n)SortedNo

*Amortized — occasional O(n) during resize

implementation

methods


What are you storing?
├── Key-Value pairs?
│ ├── Need sorted keys? → TreeMap
│ ├── Need insertion order? → LinkedHashMap
│ └── Best performance? → HashMap
├── Unique elements only?
│ ├── Need sorted order? → TreeSet
│ ├── Need insertion order? → LinkedHashSet
│ └── Best performance? → HashSet
├── Ordered elements (duplicates OK)?
│ ├── Frequent random access? → ArrayList
│ ├── Frequent insert/delete? → LinkedList
│ └── Need thread safety? → Collections.synchronizedList()
└── Processing queue?
├── Priority-based? → PriorityQueue
└── FIFO / both ends? → ArrayDeque
// Diamond operator (Java 7+)
List<String> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
// Immutable factory methods (Java 9+)
List<String> list = List.of("a", "b", "c");
Set<Integer> set = Set.of(1, 2, 3);
Map<String, Integer> map = Map.of("one", 1, "two", 2);
// Quick mutable list from array
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
// Remove duplicates from a list
Set<String> unique = new HashSet<>(listWithDuplicates);

methods

Collections.sort(list);
Collections.sort(list, comparator);
Collections.reverse(list);
int idx = Collections.binarySearch(sortedList, key);
String min = Collections.min(collection);
int count = Collections.frequency(collection, item);
boolean noCommon = Collections.disjoint(coll1, coll2);