LearnFrenzy
Sign in Take a free test

Streams API · Streams API Programs · Question 9

Price range and spread with Collectors.teeing in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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()));
    }
}

Output Verified by compiling and running

Accessories  USB Hub      -> USB Hub      spread 0
Mice         Basic Mouse  -> Gaming Mouse spread 3,200
Monitors     FHD Monitor  -> 4K Monitor   spread 20,000

teeing feeds every element to two collectors and merges their results, so min and max come from a single pass per group.

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