×

java · level 2 · unit 5 · 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

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.