java · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Sort the race times. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> times = new ArrayList<>(List.of(58, 49, 61, 52));
Collections.sort(times);
System.out.println(times);
System.out.println("58 is at index " + times.indexOf(58));
}
}
your turn
Your turn. Who is on the team?
Type any name on line 5 to search for. Press run to see the sorted team and where your name is. Try one that is missing too.
output
press run to see what happens
fix it
The snack list refuses to grow. Fix it!
output
press run to see what happens
- Java stopped with an
UnsupportedOperationExceptionon line 5. What kind of list doesList.ofmake? List.ofmakes a fixed list. It can never grow, so.addis not allowed. Wrap it in a list that can.- Change line 4 to
ArrayList<String> snacks = new ArrayList<>(List.of("popcorn", "crisps"));, then press run.
nailed it
you searched and sorted like a pro. :D
.containsand.indexOfsearch a list for you.Collections.sortputs a list in order, capitals first.List.ofis fixed. Wrap it innew ArrayList<>()to change it.
new words in your collection
- indexOf
- Collections
- List.of
This lesson isn’t saved. A free account remembers every lesson you finish.