Crash Courses · Masters
Collections: ArrayList, HashMap & Streams
Use Java's most important data structures and transform data with the Streams API — filter, map, sort, collect.
18 min read+180 XP on completionCert: Java / Kotlin Crash Course
Tap any word in the text below to start reading from there.
Collections: ArrayList, HashMap & Streams
ArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add(1, "Zara"); // insert at index 1
System.out.println(names); // [Alice, Zara, Bob, Charlie]
System.out.println(names.get(0)); // Alice
System.out.println(names.size()); // 4
names.remove("Bob"); // remove by value
names.remove(0); // remove by index
System.out.println(names); // [Zara, Charlie]
// Initialize with values (immutable):
List<Integer> scores = List.of(92, 85, 78, 96, 88);
// Mutable copy:
List<Integer> mutableScores = new ArrayList<>(scores);
Collections.sort(mutableScores);
System.out.println(mutableScores); // [78, 85, 88, 92, 96]---
HashMap
import java.util.HashMap;
import java.util.Map;
Map<String, Integer> inventory = new HashMap<>();
inventory.put("apples", 50);
inventory.put("bananas", 30);
inventory.put("oranges", 45);
System.out.println(inventory.get("apples")); // 50
System.out.println(inventory.getOrDefault("grapes", 0)); // 0 (key not present)
System.out.println(inventory.containsKey("bananas")); // true
// Update with merge:
inventory.merge("apples", 10, Integer::sum); // apples = 50 + 10 = 60
// Iterate entries:
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.printf("%s: %d%n", entry.getKey(), entry.getValue());
}
// Or with forEach lambda:
inventory.forEach((item, qty) ->
System.out.printf(" %s → %d units%n", item, qty));---
The Streams API
Streams provide a functional, declarative way to process collections. Key rule: streams don't mutate the source — they produce new results.
import java.util.List;
import java.util.stream.Collectors;
List<String> words = List.of("apple", "banana", "avocado", "blueberry", "apricot");
// filter → map → sorted → collect
List<String> result = words.stream()
.filter(w -> w.startsWith("a")) // keep words starting with 'a'
.map(String::toUpperCase) // uppercase each
.sorted() // alphabetical order
.collect(Collectors.toList());
System.out.println(result); // [APPLE, APRICOT, AVOCADO]Numeric streams and reduction:
List<Integer> nums = List.of(3, 7, 2, 9, 4, 1, 8, 5, 6);
int sum = nums.stream().mapToInt(Integer::intValue).sum();
int max = nums.stream().mapToInt(Integer::intValue).max().getAsInt();
double avg = nums.stream().mapToInt(Integer::intValue).average().getAsDouble();
System.out.printf("Sum=%d, Max=%d, Avg=%.1f%n", sum, max, avg);
// Sum=45, Max=9, Avg=5.0groupingBy — partition data into a map:
List<String> fruits = List.of("apple", "apricot", "banana", "blueberry", "cherry", "avocado");
Map<Character, List<String>> byFirstLetter = fruits.stream()
.collect(Collectors.groupingBy(s -> s.charAt(0)));
byFirstLetter.forEach((letter, list) ->
System.out.println(letter + ": " + list));
// a: [apple, apricot, avocado]
// b: [banana, blueberry]
// c: [cherry]Chaining with objects:
record Product(String name, double price, String category) {}
List<Product> products = List.of(
new Product("Laptop", 1299.0, "Electronics"),
new Product("Phone", 799.0, "Electronics"),
new Product("Desk", 450.0, "Furniture"),
new Product("Monitor", 599.0, "Electronics"),
new Product("Chair", 299.0, "Furniture")
);
// Electronics sorted by price descending, names only
List<String> elecNames = products.stream()
.filter(p -> p.category().equals("Electronics"))
.sorted((a, b) -> Double.compare(b.price(), a.price()))
.map(Product::name)
.collect(Collectors.toList());
System.out.println(elecNames); // [Laptop, Monitor, Phone]
// Total value of all products
double total = products.stream()
.mapToDouble(Product::price)
.sum();
System.out.printf("Total: $%.2f%n", total); // Total: $3446.00---
Choosing the Right Collection
| Use Case | Collection |
|---|---|
| Ordered list, indexed access | ArrayList |
| Frequent insert/delete in middle | LinkedList |
| No duplicates, fast lookup | HashSet |
| No duplicates, sorted | TreeSet |
| Key → value mapping | HashMap |
| Key → value, sorted by key | TreeMap |
| Thread-safe map | ConcurrentHashMap |
Reading progress
0% read
In this module
Generics
ArrayList
HashMap
Stream
0%