Java Collections Cheat Sheet

Overview of Java Collections Framework



  • Collection Interface: The root of the collection hierarchy. Includes methods like add(), remove(), size(), contains(), etc.
  • Collections Class: A utility class to operate on collections, e.g., Collections.sort(), Collections.reverse().
  • Iterator Interface: Used to iterate over collections. Includes methods hasNext(), next(), and remove().

Collections Hierarchy



Collection Interface


  • List Interface
    • ArrayList
    • LinkedList
    • Vector
    • Stack
  • Set Interface
    • HashSet
    • LinkedHashSet
    • TreeSet
  • Queue Interface
    • PriorityQueue
    • Deque Interface
      • ArrayDeque
  • Map Interface
    • HashMap
    • LinkedHashMap
    • TreeMap
    • Hashtable
    • ConcurrentHashMap

Collections

Collection Interface Ordered Sorted Thread safe Duplicate Nullable
ArrayList List Y N N Y Y
Vector List Y N Y Y Y
LinkedList List, Deque Y N N Y Y
HashSet Set N N N N One null
LinkedHashSet Set Y N N N One null
TreeSet Set Y Y N N N
HashMap Map N N N N (key) One null (key)
HashTable Map N N Y N (key) N (key)
LinkedHashMap Map Y N Y N (key) One null (key)
TreeMap Map Y Y Y N (key) N (key)
ArrayDeque Deque Y N N Y N
PriorityQueue Queue Y N N Y N

Common List Operations



Java
Copy
List<String> list = new ArrayList<>();

// To add element
list.add("A");

// To access element by index
list.get(0);

// To modify element at index
list.set(0, "B");

// To remove element by index
list.remove(0);

// To get size of the list
list.size();

// To check if list contains an element
list.contains("A");

// To get index of element
list.indexOf("A");

// To sort the list
Collections.sort(list);

List Interface

  • ArrayList:
    • Dynamic array, resizable.
    • Fast random access (O(1)), slow insertion/deletion (O(n)).
    • Not synchronized, allows duplicates.
  • LinkedList:
    • Doubly linked list.
    • Fast insertion/deletion (O(1)), slow random access (O(n)).
    • Can be used as a queue (implements Deque).
  • Vector:
    • Synchronized, thread-safe.
    • Slower than ArrayList for single-threaded operations.
  • Stack:
    • LIFO (Last-In-First-Out) data structure.
    • Inherits from Vector.

ArrayList

Java
Copy
List<Integer> myNumArray = new ArrayList<>();

// Adding item to arraylist
myNumArray.add(3);
myNumArray.add(5);
myNumArray.add(9);

// Retrieving first item
int firstNum = myNumArray.get(0);
System.out.println(firstNum);

// Indexed loop
for (int i = 0; i < myNumArray.size(); i++)
{
	System.out.println(myNumArray.get(i));
}

//Removing last item from array
myNumArray.remove(myNumArray.size() - 1);

//For each loop
for (Integer value : myNumArray)
{
	System.out.println(value);
}

LinkedList

Java
Copy
LinkedList<String> myFlowers = new LinkedList<>();

//Add elements
myFlowers.add("Rose");
myFlowers.addLast("Lily");
myFlowers.addFirst("Lotus");

for (String flower : myFlowers)
{
	System.out.println(flower);
}
//Retrieves, but does not remove, the first element of this list, 
//or returns null if this list is empty.
myFlowers.peekFirst();

//Retrieves, but does not remove, the last element of this list
// Returns null if this list is empty.
myFlowers.peekLast();

//Removes and returns the first element from this list.
myFlowers.removeFirst();

//Removes and returns the last element from this list.
myFlowers.removeLast();

Vector

Java
Copy
Vector<String> myVector = new Vector<>();
//Adding elements using add() method of List
myVector.add("Apple");
myVector.add("Banana");

//Adding elements using addElement() method of Vector
myVector.addElement("Cherry");
myVector.addElement("Mango");

//Getting element at index 0
System.out.println(myVector.get(0));

//Getting first element
System.out.println(myVector.firstElement());

//Getting last element
System.out.println(myVector.lastElement());

//Looping through elements
for (String s : myVector)
{
	System.out.println(s);
}

Stack



Java
Copy
// To create a new stack
Stack<Integer> myStack = new Stack<>();

// To push elements onto the stack
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);

// To pop elements from the stack
while(!myStack.isEmpty()) 
{
	System.out.println(myStack.pop());
}

Set Interface



  • HashSet:
    • Unordered collection, backed by a hash table.
    • No duplicates allowed.
    • Allows null values.
  • LinkedHashSet:
    • Ordered version of HashSet.
    • Maintains insertion order.
  • TreeSet:
    • Sorted set, backed by a TreeMap.
    • No duplicates, sorted in natural order or via a comparator.
    • Does not allow null values.

Common Set Operations



Java
Copy
Set<String> mySet = new HashSet<>();

// To add element
mySet.add("A");

// To remove element
mySet.remove("A");

// To check if set contains an element
mySet.contains("A");

// To get size of the set
mySet.size();

// Union of two sets
mySet.addAll(anotherSet);

// Intersection of two sets
mySet.retainAll(anotherSet);

// Difference between two sets
mySet.removeAll(anotherSet);

HashSet

Java
Copy
Set<String> mySet=new HashSet<>();

//Adding item to set
mySet.add("Sunday");
mySet.add("Monday");
mySet.add("Tuesday");

//Looping through set
for (String s : mySet)
{
	System.out.println(s);
}


//Remove the given item from set
mySet.remove("Monday");

LinkedHashSet

Java
Copy
LinkedHashSet<String> myLSet=new LinkedHashSet<>();

//Adding item to set
myLSet.add("Sunday");
myLSet.add("Monday");
myLSet.add("Tuesday");

//Looping through set
for (String s : myLSet)
{
	System.out.println(s);
}

//Remove the given item from set
myLSet.remove("Monday");

TreeSet

Java
Copy
TreeSet<String> myTreeSet =new TreeSet<String>();

myTreeSet.add("January");
myTreeSet.add("February");
myTreeSet.add("March");
myTreeSet.add("April");

//Returns the first (lowest) element currently in this set.
String first = myTreeSet.first();
System.out.println(first);

//Returns the last (highest) element currently in this set.
String last = myTreeSet.last();
System.out.println(last);

//Retrieves and removes the first (lowest) element,
// or returns null if this set is empty.
String pollFirst = myTreeSet.pollFirst();
System.out.println(pollFirst);

//Retrieves and removes the last (highest) element,
// or returns null if this set is empty.
String pollLast = myTreeSet.pollLast();
System.out.println(pollLast);

//Returns a reverse order view of the elements contained in this set.
myTreeSet.descendingSet();

Map Interface



  • HashMap:
    • Unordered key-value pairs, backed by a hash table.
    • Allows null keys and values.
    • Not synchronized.
  • LinkedHashMap:
    • Ordered version of HashMap.
    • Maintains insertion order.
  • TreeMap:
    • Sorted key-value pairs, backed by a TreeMap.
    • Does not allow null keys.
  • Hashtable:
    • Synchronized version of HashMap.
    • Does not allow null keys or values.
  • ConcurrentHashMap:
    • Thread-safe version of HashMap.
    • Performs better than Hashtable.

Common Map Operations



Java
Copy
Map<String, Integer> map = new HashMap<>();

// Add key-value pair
map.put("A", 1);

// Get value by key
map.get("A");

// Remove key-value pair
map.remove("A");

// Check if map contains a key
map.containsKey("A");

// Check if map contains a value
map.containsValue(1);

// Get size of the map
map.size();

// Get set of keys
map.keySet();

// Get collection of values
map.values();

// Get set of key-value pairs
map.entrySet();

HashMap

Java
Copy
//Creating HashMap
HashMap<String, Integer> myMap=new HashMap<>();

//Put elements in Map
myMap.put("Mango", 10);
myMap.put("Apple", 12);
myMap.put("Banana", 2);
myMap.put("Grapes", 2);

//Get value
int appleCount = myMap.get("Apple");
System.out.println(appleCount);

//Replace value
myMap.replace("Banana", 4);

//Returns true if this map contains a mapping for the specified key.
boolean isExist = myMap.containsKey("Orange");
System.out.println(isExist);

//Looping through each key value pair
for (Map.Entry<String, Integer> m : myMap.entrySet())
{
	System.out.println(m.getKey() + ":" + m.getValue());
}

HashTable

Java
Copy
//Creating HashTable
Hashtable<String,Integer> myHashTable=new Hashtable<String,Integer>();

//Put elements
myHashTable.put("January", 31);
myHashTable.put("February", 28);
myHashTable.put("March", 31);
myHashTable.put("April", 30);

//Get value
int vals= myHashTable.get("January");
System.out.println(vals);

//Replace value
myHashTable.replace("February", 29);

//Returns true if this map contains a mapping for the specified key.
boolean isExist = myHashTable.containsKey("March");
System.out.println(isExist);

//Looping through each key value pair
for(Map.Entry<String,Integer> m:myHashTable.entrySet())
{
	System.out.println(m.getKey()+ " : " + m.getValue());
}

LinkedHashMap

Java
Copy
//Creating LinkedHashMap
LinkedHashMap<Integer,String> myLHashMap=new LinkedHashMap<Integer,String>();

//Put elements
myLHashMap.put(1,"One");
myLHashMap.put(2,"Two");
myLHashMap.put(3,"Three");

//Get value
String vals = myLHashMap.get(2);
System.out.println(vals);

//Looping through each key value pair
for(Map.Entry<Integer, String> m:myLHashMap.entrySet())
{
	System.out.println(m.getKey()+" "+m.getValue());
}

TreeMap

Java
Copy
//Creating TreeMap
TreeMap<Integer,String> myTreeMap=new TreeMap<>();

//Put elements
myTreeMap.put(1,"One");
myTreeMap.put(2,"Two");
myTreeMap.put(3,"Three");

//Get value
String vals = myTreeMap.get(2);
System.out.println(vals);

//Looping through each key value pair
for(Map.Entry<Integer, String> m:myTreeMap.entrySet())
{
	System.out.println(m.getKey()+" "+m.getValue());
}

Queue Interface



  • PriorityQueue:
    • Elements ordered according to their natural ordering or by a comparator.
    • Implements a priority heap.
  • Deque Interface:
    • ArrayDeque:
      • Resizable array, can be used as a stack or queue.
      • Faster than Stack and LinkedList for stack operations.

Common Queue Operations



Java
Copy
Queue<String> queue = new LinkedList<>();
// Add element to the queue
queue.offer("A");

// Remove and return the head of the queue
queue.poll();

// Retrieve the head of the queue without removing it
queue.peek();

// Check if the queue is empty
queue.isEmpty();

ArrayDeque

Java
Copy
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Monday");
deque.add("Tuesday");
deque.add("Wednesday");

//Inserts the specified element at the front of this deque
deque.addFirst("Sunday");

//Inserts the specified element at the end of this deque
deque.addLast("Saturday");

//Retrieves, but does not remove, the first element of this deque.
String first = deque.getFirst();
System.out.println(first);

//Retrieves, but does not remove, the last element of this deque.
String last = deque.getLast();
System.out.println(last);

//Retrieves and removes the first element of this deque,
// or returns null if this deque is empty.
String firstPoll = deque.pollFirst();
System.out.println(firstq);

//Retrieves and removes the last element of this deque,
// or returns null if this deque is empty.
String lastPoll = deque.pollLast();
System.out.println(lastPoll);

//Traversing elements
for (String str : deque)
{
	System.out.println(str);
}

PriorityQueue

Java
Copy
//Creating PriorityQueue and adding elements
PriorityQueue<String> myPqueue=new PriorityQueue<>();
myPqueue.add("January");
myPqueue.add("February");
myPqueue.add("March");
myPqueue.add("April");

//Retrieves, but does not remove, the head of this queue.
System.out.println(myPqueue.element());

//Retrieves, but does not remove, the head of this queue,
// or returns null if this queue is empty.
System.out.println(myPqueue.peek());

//Traversing elements
for (String s : myPqueue)
{
	System.out.println(s);
}

//Retrieves and removes the head of this queue.
myPqueue.remove();

//Retrieves and removes the head of this queue,
// or returns null if this queue is empty.
myPqueue.poll();