×

java · level 2 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Lists can search themselves, and sorts them.

No more loops and flags to search. .contains("Ben") says true or false, and gives his index, or -1 when he is missing.

The Collections toolbox works on whole lists. Collections.sort(names) puts them in order: numbers smallest first, text A to Z, with capitals before small letters. Collections.reverse flips a list, and Collections.max finds the biggest item.

makes a list in one line, but it is fixed: adding or sorting stops with UnsupportedOperationException. For a list you can change, wrap it: new ArrayList<>(List.of("Zoe", "Ben")).

import java.util.*;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>(List.of("Zoe", "amy", "Ben"));
        System.out.println(names.contains("Ben") + " " + names.indexOf("Ben"));
        Collections.sort(names);
        System.out.println(names);
        Collections.reverse(names);
        System.out.println(names + " " + Collections.max(names));
    }
}

import java.util.*; borrows every tool in java.util at once, lists and Collections included.