Sub topic 9
Lambdas in Everyday Collection Code
You already know how to write lambdas and method references. Now you will use them where they help most: in everyday work with lists and maps. Since Java 8, the List and Map types have methods that take a lambda as an argument. These methods let you replace short loops with one clear line.
The Methods You Will Use Most
Each of these methods expects a functional interface, so you can pass it a lambda or a method reference.
| Method | What it does | Interface it takes |
|---|---|---|
| `list.removeIf(...)` | Removes every element that matches a test | `Predicate<T>` |
| `list.replaceAll(...)` | Replaces each element with a new value | `UnaryOperator<T>` |
| `list.sort(...)` | Sorts the list in place | `Comparator<T>` |
| `list.forEach(...)` | Runs an action on each element | `Consumer<T>` |
| `map.computeIfAbsent(...)` | Creates a value for a key if none exists yet | `Function<K, V>` |
A method that works "in place" changes the list itself. It does not build a new list.
A Worked Example
This program cleans up a list of names, sorts it, prints it, and then groups the names by length.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EverydayCollections {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Ann", "bob", "Cy", "dave"));
names.removeIf(n -> n.length() < 3); // [Ann, bob, dave]
names.replaceAll(String::toUpperCase); // [ANN, BOB, DAVE]
names.sort((a, b) -> b.compareTo(a)); // [DAVE, BOB, ANN]
names.forEach(System.out::println); // prints one name per line
Map<Integer, List<String>> byLength = new HashMap<>();
for (String n : names) {
byLength.computeIfAbsent(n.length(), k -> new ArrayList<>()).add(n);
}
System.out.println(byLength); // {3=[BOB, ANN], 4=[DAVE]}
}
}Here is what each step does:
removeIftests each name. "Cy" is shorter than 3 letters, so it is removed.replaceAllcallstoUpperCaseon every name and stores the result back in the list.sortuses a comparator that puts names in reverse alphabetical order.forEachpasses each name toSystem.out::println.computeIfAbsentgets the list stored for a length. If no list exists yet, it creates one first.
How computeIfAbsent Works
computeIfAbsent is the method that confuses beginners most. It always returns the value stored for the key, so you can call .add(n) right after it. The lambda k -> new ArrayList<>() only runs when the key is missing.
Without this method, you would need an if check, a put, and a get for every key.
Maps Have forEach Too
Map.forEach takes a BiConsumer. A BiConsumer is a consumer that receives two values, here the key and the value:
import java.util.HashMap;
import java.util.Map;
public class MapForEach {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
stock.put("apple", 5);
stock.put("pear", 2);
stock.forEach((fruit, count) -> System.out.println(fruit + ": " + count));
}
}Exercise
You have List<Integer> nums = new ArrayList<>(Arrays.asList(4, -1, 7, -3));. Write two lines that remove all negative numbers and then double every remaining number.
Show answer
nums.removeIf(n -> n < 0); followed by nums.replaceAll(n -> n * 2);. The list becomes [8, 14].
Exercise
In map.computeIfAbsent(key, k -> new ArrayList<>()), when does the lambda run?
Show answer
It runs only when the key has no value in the map yet. If the key already has a value, the lambda is skipped and the existing value is returned.