java · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a judge that decides which item comes first.
Collections.sort can order numbers and text, but not toys. So write a judge: a class that implements Comparator<Toy>. Its method gives a negative number when a comes first, a positive number when b does, and 0 for a tie.
Integer.compare(a.price, b.price) works that out for numbers, cheapest first. For text, gives A to Z.
Hand the judge to the list: toys.sort(new ByPrice());. Want it backwards? new ByPrice().reversed() flips the judge.
import java.util.*;
public class Main {
static class Toy {
String name;
int price;
Toy(String name, int price) { this.name = name; this.price = price; }
public String toString() { return name + " " + price; }
}
static class ByPrice implements Comparator<Toy> {
public int compare(Toy a, Toy b) { return Integer.compare(a.price, b.price); }
}
public static void main(String[] args) {
ArrayList<Toy> toys = new ArrayList<>();
toys.add(new Toy("kite", 12));
toys.add(new Toy("yo-yo", 3));
toys.add(new Toy("robot", 25));
toys.sort(new ByPrice());
System.out.println(toys);
}
} Sorting text with compareTo puts capitals first, the same as Collections.sort.
guess first
Line up the runners by name. 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 {
static class Runner {
String name;
int time;
Runner(String name, int time) { this.name = name; this.time = time; }
}
static class ByName implements Comparator<Runner> {
public int compare(Runner a, Runner b) { return a.name.compareTo(b.name); }
}
public static void main(String[] args) {
ArrayList<Runner> race = new ArrayList<>();
race.add(new Runner("Mia", 52));
race.add(new Runner("Ali", 61));
race.add(new Runner("Kai", 48));
race.sort(new ByName().reversed());
System.out.println(race.get(0).name + " " + race.get(0).time);
}
}
your turn
Your turn. Rank the films.
Finish the judge on line 10 so the film with the most stars comes first. Swapping a and b flips the order. Then press run.
output
press run to see what happens
fix it
The pets will not line up by name. Fix it!
output
press run to see what happens
- Java says
bad operand types for binary operator '-'on line 9. Can you take one word away from another? - Minus only works on numbers. Text has its own method for comparing in A to Z order.
- Change
a.name - b.nametoa.name.compareTo(b.name)on line 9, then press run.
nailed it
you sorted things your own way. :D
- A
Comparatorjudges which of two items comes first. - Use
Integer.comparefor numbers andcompareTofor text. .reversed()flips the judge, biggest first.
new words in your collection
- Comparator
- compare
- compareTo
This lesson isn’t saved. A free account remembers every lesson you finish.