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).
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!