1 · Values and control flow · 25 MIN
Lists, loops and independent results
A generic collection records the element type it accepts.
List<Integer> stores boxed integers, while int[] stores primitive values. This example returns a fresh ArrayList containing matching values in encounter order. It never removes items while traversing the input. List.of produces an unmodifiable list, which helps reveal accidental mutation but is not a substitute for an explicit ownership contract. Empty input should produce an empty list. Null elements need their own policy; the sample assumes non-null integers rather than silently accepting them.
Build a separate output collection for this contract.
Read the example
import java.util.*;
public class Main {
static List<Integer> even(List<Integer> values) {
var out = new ArrayList<Integer>();
for (int n : values) if (n % 2 == 0) out.add(n);
return out;
}
public static void main(String[] args) {
var input = List.of(0,1,2,-4);
System.out.println(even(input));
System.out.println(input);
}
}Check the expected output
[0, 2, -4] [0, 1, 2, -4]
Your challenge
Implement a threshold filter returning a new List and document your null-input policy.
Solution cost: O(n) time and up to O(n) result elements. time · Account for collection storage separately from the returned result. space
Common trap
Removing from a list inside an enhanced for loop can trigger ConcurrentModificationException.
Study the project implementation
import java.util.*;
public class Main {
static List<Integer> even(List<Integer> values) {
var out = new ArrayList<Integer>();
for (int n : values) if (n % 2 == 0) out.add(n);
return out;
}
public static void main(String[] args) {
var input = List.of(0,1,2,-4);
System.out.println(even(input));
System.out.println(input);
}
}Further reading: Official documentation
Next lesson: Records and value-oriented modeling →