Skip to content

Collections

Pasted image 20250918003910.png

Iterable

Iterable has a for each, so we can traverse using for each

Iterable Interface

The root interface for all collection types Provides the ability to get an iterator to loop over elements

public interface Iterable<T> {
    Iterator<T> iterator();
}

Collection Interface

Extends Iterable Represents a group of objects(elements). Common methods - add(), remove(), size(), contains();

List

public interface List<E> extends Collection<E>
// dynamic array
List<Integer> list = new List<>();

list.add("Hello");
list.addAll(); // can add from other collections

list.get(int index);
list.indexOf(int num);

list.remove(int num);

list.size();
list.isEmpty();
list.contains();

ArrayList

ArrayList<Integer> arr = new ArrayList<>();
ArrayList<Integer> arr = new ArrayList<>(collection);
ArrayList<Integer> arr = new ArrayList<>(int size);
List<String> arrList =  new ArrayList<>();
arrList.add("A");
arrList.add("B");

clear();
contains();
forEach(Consumer<T>);
remove();
removeLast();
removeRange(); // inclusive of start and exclusive of end

Stack

  • Extends Vector, Last in First Out
  • Legacy, use ArrayDeque instead due to lack of synchronization

LinkedList

  • Doubly linked list
  • Efficient insertions/removals at both ends
  • Implements Deque
  • Non contigous
  • Faster addition and deletion compared to ArrayList.

Vector

  • Thread Safe
  • Legacy

Set

HashSet

add();
clear();
contains();
remove();
isEmpty();

LinkedHashSet

  • Maintains insertion order of elements using a doubly linked list in addition to hash table
  • HashTable + Doubly Linked List
  • Slightly slower than HashSet due to the overhead.

HashMap

HashMap<Integer, String> hm = new HashMap<>();
hm.put(1, "Hello");
hm.put(2, "Hello");

hm.remove(1);

for(Map.Entry<Integer, String> e : hm.getEntry()) {
    System.out.println(e.getKey() + ":" + e.getValue());
}

TreeMap

  • Sorted HashMap

Consumer

A Consumer is a functional interface, that represents an operation that accepts a single input and returns no result.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Consumer<String> printName = name -> System.out.println("Name: " + name);
names.stream().forEach(printName);