Sub topic 9
Lambdas in Everyday Collection Code
So far you have learned to write lambdas and method references. This chapter shows where you will use them most: the lists and maps you work with every day. Since Java 8, collections have methods that take a lambda as an argument. These methods let you sort, filter, change, and group data in one short line.
You will learn these methods:
List.sortputs a list in order.removeIfdeletes the items that match a test.replaceAllchanges every item in a list.forEachruns an action on every item.Map.computeIfAbsentgets a value from a map, or creates it if it is missing.Map.mergeandMap.forEachare two helpful extras for maps.
Which Interface Does Each Method Want?
Each of these methods takes a functional interface as its argument. A functional interface is an interface with exactly one abstract method. If you know which interface a method wants, you know what shape your lambda must have.
| Method | Parameter type | Your lambda receives | Your lambda returns |
|---|---|---|---|
| `list.sort(c)` | `Comparator<T>` | two items `a`, `b` | an `int` (negative, zero, or positive) |
| `list.removeIf(p)` | `Predicate<T>` | one item | `true` to remove it |
| `list.replaceAll(op)` | `UnaryOperator<T>` | one item | the new item |
| `list.forEach(action)` | `Consumer<T>` | one item | nothing |
| `map.computeIfAbsent(k, f)` | `Function<K, V>` | the missing key | the new value |
| `map.merge(k, v, f)` | `BiFunction<V, V, V>` | old value, new value | the combined value |
| `map.forEach(action)` | `BiConsumer<K, V>` | a key and its value | nothing |
You met most of these interfaces in the chapter on the core toolkit. BiFunction and BiConsumer are the two-argument versions of Function and Consumer.
Working with Lists
Here is one program that uses all four list methods. Read the comments to see the list change after each step.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListMethods {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Cy", "ann", "Bob", "dave"));
// sort: a Comparator decides the order
names.sort((a, b) -> a.compareToIgnoreCase(b));
System.out.println(names); // [ann, Bob, Cy, dave]
// removeIf: a Predicate picks the items to delete
names.removeIf(n -> n.length() < 3);
System.out.println(names); // [ann, Bob, dave]
// replaceAll: a UnaryOperator gives each item a new value
names.replaceAll(String::toUpperCase);
System.out.println(names); // [ANN, BOB, DAVE]
// forEach: a Consumer does something with each item
names.forEach(n -> System.out.println("Hello, " + n));
// Hello, ANN
// Hello, BOB
// Hello, DAVE
}
}sort
sort changes the list in place. It does not make a new list. The lambda compares two items. It returns a negative number if a should come first, a positive number if b should come first, and zero if they are equal.
If you pass null, the list is sorted in natural order. For strings, natural order is alphabetical, with capital letters before lowercase ones.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class NaturalSort {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("bob", "Ann", "cy"));
names.sort(null);
System.out.println(names); // [Ann, bob, cy]
}
}removeIf
removeIf replaces a loop that many beginners get wrong. Before Java 8, you needed an Iterator to remove items safely. Now you only describe which items to remove. The method returns true if it removed anything.
replaceAll
replaceAll keeps the list the same size. It swaps each item for whatever your lambda returns. The new value must have the same type as the list's items. You cannot turn a List<String> into a List<Integer> this way.
forEach
forEach is the shortest way to visit every item. The method reference System.out::println is a common choice:
import java.util.Arrays;
import java.util.List;
public class PrintAll {
public static void main(String[] args) {
List<Integer> scores = Arrays.asList(90, 75, 88);
scores.forEach(System.out::println);
// 90
// 75
// 88
}
}How removeIf Works
The diagram shows what removeIf does with your lambda. The method owns the loop. Your lambda answers one yes-or-no question per item.
Working with Maps
Maps have their own lambda methods. They solve two common jobs: grouping items and counting them.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class MapMethods {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "fig", "kiwi", "pear", "fig", "plum");
// Grouping: word length -> list of words
Map<Integer, List<String>> byLength = new TreeMap<>();
for (String w : words) {
byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
}
System.out.println(byLength); // {3=[fig, fig], 4=[kiwi, pear, plum], 5=[apple]}
// Counting: word -> how many times it appears
Map<String, Integer> counts = new TreeMap<>();
for (String w : words) {
counts.merge(w, 1, Integer::sum);
}
// Visiting every key and value
counts.forEach((word, count) -> System.out.println(word + ": " + count));
// apple: 1
// fig: 2
// kiwi: 1
// pear: 1
// plum: 1
}
}A TreeMap is a map that keeps its keys sorted. It is used here so the output always comes out in the same order.
computeIfAbsent
computeIfAbsent(key, f) does one of two things:
- If the key is already in the map, it returns the existing value. The lambda does not run.
- If the key is missing, it calls the lambda with the key, stores the result, and returns it.
Both cases return the value, so you can chain .add(w) straight after the call. Without this method, you would need an if check, a put, and a get for every word.
The lambda k -> new ArrayList<>() ignores its parameter k. That is fine, because the Function interface still requires one parameter.
merge
merge(key, value, f) also has two cases. If the key is missing, it stores value. If the key is present, it calls f with the old value and the new value, then stores the result. Integer::sum adds them, so each repeated word adds 1 to its count.
Map.forEach
Map.forEach takes a BiConsumer, so the lambda has two parameters: the key and the value. This is easier to read than looping over entrySet() and calling getKey() and getValue().
Common Mistakes
These methods are simple, but a few mistakes come up often.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.List;
public class Pitfalls {
public static void main(String[] args) {
// Mistake 1: removing from a fixed-size list
List<String> fixed = Arrays.asList("a", "bb", "ccc");
fixed.replaceAll(s -> s + "!"); // fine: the size does not change
System.out.println(fixed); // [a!, bb!, ccc!]
try {
fixed.removeIf(s -> s.length() > 2);
} catch (UnsupportedOperationException e) {
System.out.println("Cannot remove from a fixed-size list");
}
// Mistake 2: changing a list inside its own forEach
List<String> list = new ArrayList<>(Arrays.asList("a", "bb", "ccc"));
try {
list.forEach(s -> {
if (s.length() == 2) {
list.remove(s);
}
});
} catch (ConcurrentModificationException e) {
System.out.println("Do not change a list inside its own forEach");
}
}
}The second mistake throws a ConcurrentModificationException. This exception means a list was changed while it was being looped over. Use removeIf for removal, and keep forEach for actions like printing or saving.
Some other points to remember:
forEachcannot stop early. There is nobreakinside a lambda. If you need to stop at the first match, use a normalforloop.returninside aforEachlambda skips only the current item. It ends that one call of the lambda, not the whole loop.- Local variables must be effectively final. You cannot write
count++on a local variable inside aforEachlambda. Usesize(),merge, or a stream instead. computeIfAbsentstores nothing if your lambda returnsnull. The key stays missing.
These methods change the collection in place. The next chapters show how to build bigger lambdas from small ones, and how streams create new results without changing the original collection.
Exercises
Exercise
You have List<Integer> nums = new ArrayList<>(Arrays.asList(4, 7, 10, 3)). Write one line that removes all odd numbers, and one line that doubles every remaining number. What does the list contain afterward?
Show answer
nums.removeIf(n -> n % 2 != 0); then nums.replaceAll(n -> n * 2); The list becomes [8, 20]. removeIf takes a Predicate and replaceAll takes a UnaryOperator<Integer>.
Exercise
Why does List<String> list = Arrays.asList("x", "yy"); list.removeIf(s -> s.length() == 2); throw an exception, while list.replaceAll(String::toUpperCase) works?
Show answer
Arrays.asList returns a fixed-size list. replaceAll only swaps items, so the size stays the same and the call is allowed. removeIf tries to delete "yy", which would change the size, so it throws UnsupportedOperationException. Copy the list into new ArrayList<>(...) first.
Exercise
Given List<String> cities = Arrays.asList("Rome", "Oslo", "Lima", "Paris"), use a Map<Character, List<String>> and computeIfAbsent to group cities by their first letter. What should the map contain?
Show answer
for (String c : cities) { map.computeIfAbsent(c.charAt(0), k -> new ArrayList<>()).add(c); } The map contains R=[Rome], O=[Oslo], L=[Lima], P=[Paris]. With a TreeMap the order is {L=[Lima], O=[Oslo], P=[Paris], R=[Rome]}.
Exercise
A classmate writes names.forEach(n -> { if (n.equals("stop")) return; System.out.println(n); }); and expects printing to stop at "stop". What actually happens?
Show answer
The return ends only the current call of the lambda, so "stop" is skipped and the items after it are still printed. forEach cannot break out early. Use a regular for loop with break to stop at the first match.