For each product category, compute the cheapest and most expensive item in one pass using Collectors.teeing (minBy and maxBy), and print the price spread.
Solution
Main.java
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
record Product(String name, String category, int price) { }
record Range(String cheapest, String dearest, int spread) { }
public class Main {
public static void main(String[] args) {
List<Product> ps = List.of(new Product("Basic Mouse", "Mice", 299), new Product("Gaming Mouse", "Mice", 3499), new Product("Office Mouse", "Mice", 799),
new Product("4K Monitor", "Monitors", 28999), new Product("FHD Monitor", "Monitors", 8999), new Product("USB Hub", "Accessories", 999));
Map<String, Range> ranges = ps.stream().collect(Collectors.groupingBy(Product::category, TreeMap::new,
Collectors.teeing(
Collectors.minBy(Comparator.comparingInt(Product::price)),
Collectors.maxBy(Comparator.comparingInt(Product::price)),
(min, max) -> new Range(min.get().name(), max.get().name(), max.get().price() - min.get().price()))));
ranges.forEach((cat, r) -> System.out.printf("%-12s %-12s -> %-12s spread %,d%n", cat, r.cheapest(), r.dearest(), r.spread()));
}
}
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!