Home › Learn › Java › Arrays and lists

ArrayList

Lesson 18 of 40. A list that grows and shrinks.

Arrays cannot change size; ArrayList can. List<String> names = new ArrayList<>(); makes an empty list of strings (the type in angle brackets is the element type, and it must be a class, so Integer rather than int). names.add("Ada") appends, names.get(0) reads, names.size() counts, names.remove("Ada") or names.remove(0) deletes, names.contains("Ada") asks. List.of("a", "b") makes a fixed list that cannot change, handy for tests and constants.

Declare the variable as the interface List and create an ArrayList; the code then works with any list. import java.util.*; at the top of the file brings in List, ArrayList, and the rest of the collections.

import java.util.*;

List<Integer> xs = new ArrayList<>();
xs.add(3);
xs.add(5);
System.out.println(xs.size() + " " + xs.get(1) + " " + xs);   // 2 5 [3, 5]

Your task

Write static List<Integer> evens(List<Integer> xs) returning a new list of the even values in order, static List<String> unique(List<String> xs) returning a new list with each value once, in the order first seen, and static int total(List<Integer> xs) returning the sum.

Hint 1

for (int x : xs) if (x % 2 == 0) result.add(x);

Hint 2

unique: add each value only if (!result.contains(value)).

Show the solution
import java.util.*;

public class Main {
    static List<Integer> evens(List<Integer> xs) {
        List<Integer> result = new ArrayList<>();
        for (int x : xs) {
            if (x % 2 == 0) {
                result.add(x);
            }
        }
        return result;
    }

    static List<String> unique(List<String> xs) {
        List<String> result = new ArrayList<>();
        for (String x : xs) {
            if (!result.contains(x)) {
                result.add(x);
            }
        }
        return result;
    }

    static int total(List<Integer> xs) {
        int sum = 0;
        for (int x : xs) {
            sum += x;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(evens(List.of(1, 2, 3, 4)) + " " + unique(List.of("a", "b", "a")));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.