LearnFrenzy
Sign in Take a free test

Streams API · Streams API Programs · Question 6

Parse CSV inventory and report with streams in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Parse CSV lines "sku,name,category,qty,price" (skipping the header and bad rows), then print the stock value per category, items that need reordering (qty < 10) and the total inventory value.

Solution
Main.java
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Item(String sku, String name, String category, int qty, double price) {
    double value() { return qty * price; }

    static Optional<Item> parse(String line) {
        String[] f = line.split(",");
        try {
            return Optional.of(new Item(f[0], f[1], f[2], Integer.parseInt(f[3]), Double.parseDouble(f[4])));
        } catch (RuntimeException e) {
            return Optional.empty();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        String csv = """
            sku,name,category,qty,price
            P1,Pen,Stationery,250,10
            P2,Notebook,Stationery,8,60
            E1,Mouse,Electronics,40,699
            E2,Monitor,Electronics,3,9999
            X9,Broken,Misc,abc,1
            F1,Desk,Furniture,6,7499
            """;
        var items = csv.lines().skip(1).map(Item::parse).flatMap(Optional::stream).toList();

        Map<String, Double> byCat = items.stream().collect(Collectors.groupingBy(Item::category, TreeMap::new, Collectors.summingDouble(Item::value)));
        byCat.forEach((c, v) -> System.out.printf("%-12s %,10.2f%n", c, v));
        System.out.println("reorder: " + items.stream().filter(i -> i.qty() < 10).map(i -> i.name() + "(" + i.qty() + ")").collect(Collectors.joining(", ")));
        System.out.printf("total %,.2f from %d valid rows%n", items.stream().mapToDouble(Item::value).sum(), items.size());
    }
}

Output Verified by compiling and running

Electronics   57,957.00
Furniture     44,994.00
Stationery     2,980.00
reorder: Notebook(8), Monitor(3), Desk(6)
total 105,931.00 from 5 valid rows

Returning Optional from the parser and using flatMap(Optional::stream) silently drops the bad row.

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