Java Collections & Essential Methods

List, Set, Map, Queue, Stack, Streams, String methods, Arrays, and daily-use utility functions

Language / Daily Use
Contents
πŸ—οΈ

Collections Hierarchy

Iterable β”‚ Collection β•± β”‚ β•² List Set Queue β”‚ β”‚ β”‚ ArrayList HashSet PriorityQueue LinkedList TreeSet ArrayDeque Vector LinkedHashSet Stack Map (separate hierarchy) β”‚ HashMap TreeMap LinkedHashMap ConcurrentHashMap
πŸ’‘ Quick picking guide
  • ArrayList: Default choice for ordered, indexed access. O(1) get, O(n) insert middle.
  • LinkedList: Frequent insert/delete at ends. O(n) get, O(1) add/remove first/last.
  • HashSet: Unique elements, no order. O(1) add/contains/remove.
  • TreeSet: Unique + sorted. O(log n) operations.
  • HashMap: Key-value pairs. O(1) get/put. Most used Map.
  • TreeMap: Sorted keys. O(log n) operations.
  • PriorityQueue: Min-heap. O(log n) add/poll.
πŸ“‹

List (ArrayList, LinkedList)

import java.util.*;

// Creation
List<String> list = new ArrayList<>();
List<String> list2 = List.of("a", "b", "c");       // immutable
List<String> list3 = new ArrayList<>(List.of("a", "b"));  // mutable copy

// ── Add ──
list.add("Alice");            // append
list.add(0, "Bob");           // insert at index
list.addAll(List.of("C", "D"));

// ── Access ──
list.get(0);                   // by index
list.getFirst();               // Java 21+
list.getLast();                // Java 21+
list.indexOf("Alice");         // first occurrence (-1 if not found)
list.lastIndexOf("Alice");

// ── Remove ──
list.remove(0);                // by index
list.remove("Alice");          // by value (first occurrence)
list.removeIf(s -> s.startsWith("A"));
list.clear();

// ── Query ──
list.size();
list.isEmpty();
list.contains("Alice");
list.containsAll(List.of("A", "B"));

// ── Modify ──
list.set(0, "Updated");       // replace at index
list.sort(Comparator.naturalOrder());
list.sort(Comparator.comparing(String::length));
Collections.reverse(list);
Collections.shuffle(list);

// ── Iterate ──
for (String s : list) { }
for (int i = 0; i < list.size(); i++) { list.get(i); }
list.forEach(System.out::println);

// ── Sublist & Convert ──
list.subList(0, 2);            // view [0, 2)
list.toArray(new String[0]);   // to array
String.join(", ", list);       // join to string
πŸ”΅

Set (HashSet, TreeSet, LinkedHashSet)

// Creation
Set<String> set = new HashSet<>();
Set<String> sorted = new TreeSet<>();          // sorted
Set<String> ordered = new LinkedHashSet<>();    // insertion order
Set<String> immutable = Set.of("a", "b", "c");

// ── Operations ──
set.add("Alice");       // returns false if already exists
set.remove("Alice");
set.contains("Alice");
set.size();
set.isEmpty();

// ── Set Math ──
Set<Integer> a = new HashSet<>(Set.of(1,2,3));
Set<Integer> b = Set.of(2,3,4);

a.retainAll(b);                // intersection: {2, 3}
a.addAll(b);                   // union: {1, 2, 3, 4}
a.removeAll(b);                // difference: {1}

// Convert
List<String> fromSet = new ArrayList<>(set);
Set<String> fromList = new HashSet<>(list);
πŸ—ΊοΈ

Map (HashMap, TreeMap, LinkedHashMap)

// Creation
Map<String, Integer> map = new HashMap<>();
Map<String, Integer> sorted = new TreeMap<>();      // sorted keys
Map<String, Integer> ordered = new LinkedHashMap<>();  // insertion order
Map<String, Integer> immutable = Map.of("a", 1, "b", 2);

// ── Put / Get ──
map.put("Alice", 95);
map.putIfAbsent("Bob", 87);      // only if key not present
map.get("Alice");                  // null if missing
map.getOrDefault("Charlie", 0);   // default if missing

// ── Remove ──
map.remove("Alice");
map.remove("Alice", 95);          // only if value matches

// ── Query ──
map.containsKey("Alice");
map.containsValue(95);
map.size();
map.isEmpty();

// ── Compute / Merge ──
map.compute("Alice", (k, v) -> v == null ? 1 : v + 1);
map.computeIfAbsent("key", k -> expensiveCalculation());
map.merge("Alice", 10, Integer::sum);  // add to existing

// ── Iterate ──
for (Map.Entry<String, Integer> e : map.entrySet()) {
    e.getKey(); e.getValue();
}
map.forEach((k, v) -> System.out.println(k + "=" + v));
map.keySet();    // Set<String>
map.values();    // Collection<Integer>
map.entrySet();  // Set<Entry>

// ── Word frequency counter (classic pattern) ──
Map<String, Integer> freq = new HashMap<>();
for (String word : words) {
    freq.merge(word, 1, Integer::sum);
}
πŸ“¬

Queue & Deque

// Queue (FIFO)
Queue<String> queue = new LinkedList<>();
queue.offer("first");   // add to tail
queue.peek();            // view head (null if empty)
queue.poll();            // remove head (null if empty)

// PriorityQueue (min-heap by default)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
minHeap.offer(5); minHeap.offer(1); minHeap.offer(3);
minHeap.poll();   // 1 (smallest)

// Custom comparator
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);

// Deque (double-ended queue)
Deque<String> deque = new ArrayDeque<>();
deque.offerFirst("front");
deque.offerLast("back");
deque.peekFirst();
deque.peekLast();
deque.pollFirst();
deque.pollLast();
πŸ“š

Stack

// Use ArrayDeque as stack (preferred over Stack class)
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);           // push to top
stack.push(2);
stack.peek();            // 2 (view top)
stack.pop();             // 2 (remove top)
stack.isEmpty();

// Classic pattern: valid parentheses
public boolean isValid(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (c == '(') stack.push(')');
        else if (c == '[') stack.push(']');
        else if (c == '{') stack.push('}');
        else if (stack.isEmpty() || stack.pop() != c) return false;
    }
    return stack.isEmpty();
}
🌊

Streams API

List<String> names = List.of("Alice", "Bob", "Charlie", "Alice");

// filter + map + collect
List<String> upper = names.stream()
    .filter(n -> n.length() > 3)
    .map(String::toUpperCase)
    .distinct()
    .sorted()
    .collect(Collectors.toList());

// reduce
int sum = List.of(1,2,3,4).stream().reduce(0, Integer::sum);

// groupingBy
Map<Integer, List<String>> byLength = names.stream()
    .collect(Collectors.groupingBy(String::length));
// {3=[Bob], 5=[Alice, Alice], 7=[Charlie]}

// counting
Map<String, Long> freq = names.stream()
    .collect(Collectors.groupingBy(n -> n, Collectors.counting()));

// toMap
Map<String, Integer> nameLen = names.stream()
    .distinct()
    .collect(Collectors.toMap(n -> n, String::length));

// joining
String joined = names.stream().collect(Collectors.joining(", "));

// anyMatch, allMatch, noneMatch
boolean hasAlice = names.stream().anyMatch(n -> n.equals("Alice"));

// findFirst, findAny
Optional<String> first = names.stream()
    .filter(n -> n.startsWith("C"))
    .findFirst();

// flatMap (flatten nested collections)
List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4));
List<Integer> flat = nested.stream()
    .flatMap(Collection::stream)
    .toList();  // [1, 2, 3, 4]

// IntStream, range
IntStream.range(0, 10).forEach(System.out::println);
IntStream.rangeClosed(1, 100).sum();

// Parallel stream
long count = list.parallelStream().filter(x -> x > 0).count();
πŸ“

String Methods

String s = "Hello, World!";

// ── Basics ──
s.length();                    // 13
s.charAt(0);                   // 'H'
s.substring(0, 5);             // "Hello"
s.indexOf("World");             // 7
s.lastIndexOf("l");             // 10
s.contains("World");            // true
s.isEmpty();                    // false
s.isBlank();                    // false (Java 11+)  "  ".isBlank() = true

// ── Transform ──
s.toUpperCase();               // "HELLO, WORLD!"
s.toLowerCase();
s.trim();                      // remove leading/trailing whitespace
s.strip();                     // Unicode-aware trim (Java 11+)
s.replace("World", "Java");
s.replaceAll("[aeiou]", "*"); // regex
s.repeat(3);                   // Java 11+

// ── Split & Join ──
String[] parts = s.split(", ");
String.join("-", "a", "b", "c");  // "a-b-c"

// ── Compare ──
s.equals("Hello");              // case-sensitive
s.equalsIgnoreCase("hello, world!");
s.startsWith("Hello");
s.endsWith("!");
s.compareTo("other");           // lexicographic
s.matches("[A-Za-z ]+");        // regex match

// ── Format ──
String.format("Name: %s, Age: %d", "Alice", 30);
String.valueOf(42);             // int to String
Integer.parseInt("42");          // String to int

// StringBuilder (mutable, efficient concatenation)
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" World");
sb.insert(5, ",");
sb.reverse();
sb.toString();
πŸ“Š

Arrays Utility

import java.util.Arrays;

int[] arr = {5, 3, 1, 4, 2};

Arrays.sort(arr);                     // in-place sort
Arrays.sort(arr, 0, 3);               // sort range [0,3)
Arrays.binarySearch(arr, 3);          // must be sorted first
Arrays.fill(arr, 0);                  // fill with 0
Arrays.copyOf(arr, 10);               // copy with new length
Arrays.copyOfRange(arr, 1, 4);        // copy range
Arrays.equals(arr, other);             // compare
Arrays.toString(arr);                  // "[1, 2, 3, 4, 5]"
Arrays.stream(arr).sum();              // stream operations
Arrays.asList("a", "b", "c");       // array to List

// 2D arrays
int[][] matrix = new int[3][4];
Arrays.deepToString(matrix);
Arrays.sort(matrix, (a, b) -> a[0] - b[0]);  // sort by first column
πŸ”§

Collections Utility Class

import java.util.Collections;

Collections.sort(list);
Collections.reverse(list);
Collections.shuffle(list);
Collections.min(list);
Collections.max(list);
Collections.frequency(list, "Alice");
Collections.swap(list, 0, 1);
Collections.rotate(list, 2);
Collections.binarySearch(sortedList, "key");

// Immutable wrappers
List<String> unmod = Collections.unmodifiableList(list);
Map<String, Integer> unmodMap = Collections.unmodifiableMap(map);

// Thread-safe wrappers
List<String> syncList = Collections.synchronizedList(new ArrayList<>());

// Singleton & empty
List<String> single = Collections.singletonList("only");
List<String> empty = Collections.emptyList();
❓

Optional

Optional<String> opt = Optional.of("Hello");
Optional<String> empty = Optional.empty();
Optional<String> nullable = Optional.ofNullable(getValue());

// Check & get
opt.isPresent();               // true
opt.isEmpty();                 // false (Java 11+)
opt.get();                     // "Hello" (throws if empty!)
opt.orElse("default");         // value or default
opt.orElseGet(() -> compute()); // lazy default
opt.orElseThrow();             // throw NoSuchElementException

// Transform
opt.map(String::toUpperCase);   // Optional<String>
opt.flatMap(this::findUser);    // when mapper returns Optional
opt.filter(s -> s.length() > 3);
opt.ifPresent(System.out::println);
opt.ifPresentOrElse(
    System.out::println,
    () -> System.out.println("empty")
);
πŸ•

Date & Time (java.time)

import java.time.*;
import java.time.format.DateTimeFormatter;

LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dt = LocalDateTime.now();
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("UTC"));
Instant instant = Instant.now();  // epoch millis

// Create specific
LocalDate.of(2024, 3, 15);
LocalDate.parse("2024-03-15");

// Manipulate
date.plusDays(7).minusMonths(1);
date.withYear(2025);
Duration.between(start, end);
Period.between(date1, date2);

// Format
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
dt.format(fmt);
LocalDateTime.parse("2024-03-15 10:30", fmt);
πŸ“

File I/O

import java.nio.file.*;

// Read file
String content = Files.readString(Path.of("data.txt"));
List<String> lines = Files.readAllLines(Path.of("data.txt"));

// Write file
Files.writeString(Path.of("out.txt"), "Hello");
Files.write(Path.of("out.txt"), lines);

// Stream large files
try (Stream<String> stream = Files.lines(Path.of("big.txt"))) {
    stream.filter(l -> l.contains("error")).forEach(System.out::println);
}

// Directory operations
Files.exists(path);
Files.createDirectories(Path.of("a/b/c"));
Files.list(Path.of(".")).forEach(System.out::println);
Files.walk(Path.of("src")).filter(p -> p.toString().endsWith(".java"));