Java Collections and Streams Cheat Sheet
ArrayList, HashMap, HashSet, queues, sorting with Comparator, and the most useful stream operations.
Updated
Choosing a collection#
Declare with the interface: List<String> names = new ArrayList<>();. Collections hold objects, so use Integer, not int.
List#
List<String> list = new ArrayList<>(List.of("b", "a"));
list.add("c"); // append
list.add(0, "z"); // insert at index
list.get(0); list.set(0, "y");
list.remove("a"); // by value
list.remove(0); // by index (careful with List<Integer>)
list.size(); list.isEmpty(); list.contains("b");
list.indexOf("b"); // -1 if missing
list.removeIf(s -> s.isBlank());
list.sort(Comparator.naturalOrder());
List<String> fixed = List.of("x", "y"); // unmodifiableMap#
Map<String, Integer> stock = new HashMap<>();
stock.put("pens", 40); // add or replace
stock.get("pens"); // 40, or null if missing
stock.getOrDefault("caps", 0); // 0
stock.containsKey("pens");
stock.remove("pens");
stock.putIfAbsent("bags", 5);
stock.merge("bags", 1, Integer::sum); // counting: 6
stock.computeIfAbsent("x", k -> 0);
for (Map.Entry<String, Integer> e : stock.entrySet()) {
String key = e.getKey();
int value = e.getValue();
}
stock.forEach((k, v) -> System.out.println(k + "=" + v));
TreeMap<Integer, String> grades = new TreeMap<>();
grades.floorKey(72); grades.ceilingKey(72); grades.firstKey();Set#
Set<String> seen = new HashSet<>();
boolean added = seen.add("Pune"); // false if already present
seen.contains("Pune");
seen.remove("Pune");
Set<String> both = new TreeSet<>(a); both.retainAll(b); // intersection
Set<String> either = new TreeSet<>(a); either.addAll(b); // union
Set<String> onlyA = new TreeSet<>(a); onlyA.removeAll(b); // difference
List<Integer> unique = new ArrayList<>(new LinkedHashSet<>(numbers)); // dedupe, keep orderQueue, stack and priority queue#
Queue<String> queue = new ArrayDeque<>();
queue.offer("a"); queue.peek(); queue.poll(); // poll returns null when empty
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.peek(); stack.pop(); // use instead of java.util.Stack
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap.offer(5); minHeap.poll(); // smallest firstSorting#
Collections.sort(numbers); // natural order
list.sort(Comparator.reverseOrder());
people.sort(Comparator.comparing(Person::name));
people.sort(Comparator.comparingInt(Person::age).reversed()
.thenComparing(Person::name));
class Version implements Comparable<Version> { // natural order
int major;
public int compareTo(Version o) { return Integer.compare(major, o.major); }
}Streams#
List<Integer> result = nums.stream()
.filter(n -> n > 10) // keep
.map(n -> n * 2) // transform
.sorted()
.distinct()
.limit(5)
.toList(); // Java 16+
long count = nums.stream().filter(n -> n % 2 == 0).count();
int sum = nums.stream().mapToInt(Integer::intValue).sum();
double avg = nums.stream().mapToInt(Integer::intValue).average().orElse(0);
Optional<Integer> max = nums.stream().max(Integer::compare);
boolean any = nums.stream().anyMatch(n -> n > 100);
int product = nums.stream().reduce(1, (x, y) -> x * y);
String joined = words.stream().collect(Collectors.joining(", "));
IntStream.rangeClosed(1, 100).sum(); // 5050Collectors#
Map<String, List<Sale>> byRegion = sales.stream()
.collect(Collectors.groupingBy(Sale::region));
Map<String, Long> counts = words.stream()
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
Map<String, Integer> totals = sales.stream()
.collect(Collectors.groupingBy(Sale::region, TreeMap::new, Collectors.summingInt(Sale::amount)));
Map<Boolean, List<Integer>> evenOdd = nums.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));Complexity at a glance#
* amortized
Want the full explanations? Go to the Learn Java course →