LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 2

Sort products several ways with Comparator in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Create a Product record (name, price, rating) and print the list sorted by price, by rating (high to low, then name), and by name length using Comparator factory methods.

Solution
Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

record Product(String name, int price, double rating) {
    @Override public String toString() { return name; }
}

public class Main {
    public static void main(String[] args) {
        List<Product> ps = new ArrayList<>(List.of(new Product("Mouse", 699, 4.4), new Product("Keyboard", 1499, 4.6),
                new Product("Monitor", 9999, 4.4), new Product("Cable", 199, 4.1)));

        ps.sort(Comparator.comparingInt(Product::price));
        System.out.println("by price:  " + ps);

        ps.sort(Comparator.comparingDouble(Product::rating).reversed().thenComparing(Product::name));
        System.out.println("by rating: " + ps);

        ps.sort(Comparator.comparingInt((Product p) -> p.name().length()).thenComparing(Product::price, Comparator.reverseOrder()));
        System.out.println("by length: " + ps);
    }
}

Output Verified by compiling and running

by price:  [Cable, Mouse, Keyboard, Monitor]
by rating: [Keyboard, Monitor, Mouse, Cable]
by length: [Mouse, Cable, Monitor, Keyboard]

Mouse and Cable both have 5 letters; the tie-breaker sorts by price descending, so Mouse (699) comes before Cable (199).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links