Java Collections
Java Collections Framework: ArrayList, HashMap, HashSet, and common operations.
ArrayList
// Import and create
import java.util.ArrayList;
ArrayList list = new ArrayList<>(); # dynamic array
// Add elements
list.add("Apple"); # add to end
list.add("Banana");
// Access elements
String first = list.get(0); # get by index
// Remove elements
list.remove(0); # remove by index
list.remove("Apple"); # remove by value
ArrayList Methods
// Common methods
list.size() # number of elements
list.isEmpty() # check if empty
list.contains("Apple") # check existence
list.clear() # remove all
// Set element
list.set(0, "Orange"); # replace at index
HashMap
// Import and create
import java.util.HashMap;
HashMap map = new HashMap<>(); # key-value pairs
// Add key-value pairs
map.put("John", 25); # insert/update
map.put("Jane", 30);
// Get value
int age = map.get("John"); # returns 25
// Remove entry
map.remove("John"); # delete key-value
HashMap Methods
// Common methods
map.containsKey("John") # check if key exists
map.containsValue(25) # check if value exists
map.size() # number of pairs
map.isEmpty()
map.clear()
// Get all keys and values
map.keySet() # all keys
map.values() # all values
HashSet
// Import and create
import java.util.HashSet;
HashSet set = new HashSet<>(); # unique elements only
// Add elements
set.add("Apple");
set.add("Banana");
set.add("Apple"); # duplicate ignored
// Remove element
set.remove("Apple");
Iterating Collections
// For-each loop
for (String item : list) { # iterate list
System.out.println(item);
}
// Iterate HashMap
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
LinkedList
// Import and create
import java.util.LinkedList;
LinkedList list = new LinkedList<>(); # doubly-linked
// Add to front/end
list.addFirst("First"); # add at beginning
list.addLast("Last"); # add at end
// Remove from front/end
list.removeFirst();
list.removeLast();
Collections Utility
// Import Collections
import java.util.Collections;
// Sort list
Collections.sort(list); # ascending order
// Reverse list
Collections.reverse(list); # reverse order
// Find max/min
Collections.max(list); # largest element
Collections.min(list); # smallest element