โ† Back to Courses
ยฉ 2025 sampathirao yoganandh
Week 14 ยท CO-4

Collection Classes

ArrayList, LinkedList, HashSet, TreeSet, PriorityQueue, HashMap, TreeMap, Collections class  CO-4

ArrayList

ArrayList is a resizable array implementation of List. It provides fast random access (O(1)) but slow insertions/deletions in the middle (O(n)).

import java.util.*;

ArrayList<String> cities = new ArrayList<>();
cities.add("Hyderabad");
cities.add("Vizag");
cities.add("Chennai");
cities.add(1, "Vijayawada");  // insert at index 1

Collections.sort(cities);          // alphabetical sort
cities.remove("Chennai");
System.out.println(cities);         // [Hyderabad, Vijayawada, Vizag]
System.out.println(cities.size()); // 3
๐Ÿ“Œ Key PointArrayList grows automatically when its capacity is exceeded (by 50% each time). Use ArrayList<E>(initialCapacity) when the approximate size is known.

LinkedList

LinkedList implements both List and Deque. It uses a doubly-linked node structure โ€” fast insertions/deletions (O(1)) but slow random access (O(n)).

LinkedList<Integer> ll = new LinkedList<>();
ll.addFirst(10);  ll.addLast(30);  ll.add(1, 20);
System.out.println(ll);          // [10, 20, 30]
System.out.println(ll.getFirst()); // 10
ll.removeFirst();
System.out.println(ll);          // [20, 30]

// Use as Stack (LIFO)
ll.push(99); System.out.println(ll.pop()); // 99

// Use as Queue (FIFO)
ll.offer(1); ll.offer(2); System.out.println(ll.poll()); // 1

HashSet & LinkedHashSet

FeatureHashSetLinkedHashSet
OrderNo guaranteed orderInsertion order maintained
PerformanceFastestSlightly slower
NullOne null allowedOne null allowed
DuplicateNot allowedNot allowed
Set<Integer> hs = new HashSet<>(Arrays.asList(5,3,1,4,2,3));
System.out.println(hs); // e.g. [1, 2, 3, 4, 5] โ€” order varies

Set<Integer> lhs = new LinkedHashSet<>(Arrays.asList(5,3,1,4,2,3));
System.out.println(lhs); // [5, 3, 1, 4, 2] โ€” insertion order

TreeSet

TreeSet stores elements in sorted (natural) order using a Red-Black Tree. For custom objects, implement Comparable or pass a Comparator.

TreeSet<String> ts = new TreeSet<>();
ts.add("Banana"); ts.add("Apple"); ts.add("Cherry"); ts.add("Apple");
System.out.println(ts);           // [Apple, Banana, Cherry] โ€” sorted, no dup
System.out.println(ts.first());   // Apple
System.out.println(ts.last());    // Cherry
System.out.println(ts.headSet("Cherry")); // [Apple, Banana]
๐Ÿ“Œ Key PointFor custom sorting: TreeSet<Student> set = new TreeSet<>(Comparator.comparing(s -> s.name));

PriorityQueue

PriorityQueue is a min-heap by default โ€” the smallest element is always at the head. Use a custom Comparator for max-heap or other ordering.

PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(30); pq.offer(10); pq.offer(20);

while (!pq.isEmpty())
    System.out.print(pq.poll() + " "); // 10 20 30 (min first)

// Max-heap using Comparator
PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder());
maxPQ.addAll(Arrays.asList(30,10,20));
System.out.print(maxPQ.poll()); // 30

HashMap & LinkedHashMap

HashMap<String,Integer> map = new HashMap<>();
map.put("Math", 90); map.put("Java", 95); map.put("DBMS", 88);
map.putIfAbsent("Java", 70);  // won't overwrite existing

// Iterate over key-value pairs
map.forEach((k, v) -> System.out.println(k + ": " + v));

// Get with default
int score = map.getOrDefault("Physics", 0);

// LinkedHashMap โ€” maintains insertion order
Map<String,Integer> lhm = new LinkedHashMap<>();

TreeMap

TreeMap stores key-value pairs sorted by key in natural order.

TreeMap<String,Integer> tm = new TreeMap<>();
tm.put("Charlie", 3); tm.put("Alice", 1); tm.put("Bob", 2);
System.out.println(tm);           // {Alice=1, Bob=2, Charlie=3} โ€” sorted by key
System.out.println(tm.firstKey()); // Alice
System.out.println(tm.lastKey());  // Charlie

Collections Utility Class

The java.util.Collections class provides static utility methods for collections.

MethodDescription
sort(list)Sorts list in natural order
sort(list, comparator)Sorts with custom comparator
binarySearch(list, key)Binary search (list must be sorted)
reverse(list)Reverses order of elements
shuffle(list)Randomly shuffles elements
min(collection)Returns minimum element
max(collection)Returns maximum element
frequency(c, obj)Counts occurrences of obj
unmodifiableList(list)Returns read-only view
synchronizedList(list)Returns thread-safe wrapper
List<Integer> nums = new ArrayList<>(Arrays.asList(5,2,8,1,9));
Collections.sort(nums);                             // [1,2,5,8,9]
Collections.reverse(nums);                          // [9,8,5,2,1]
System.out.println(Collections.max(nums));          // 9
System.out.println(Collections.frequency(nums, 5)); // 1

List<Integer> readOnly = Collections.unmodifiableList(nums);
// readOnly.add(10); // throws UnsupportedOperationException
๐Ÿ“„

Download PDF Notes

Save these notes as a PDF for offline reference

View / Download PDF