Skip to main content

Lesson 7 of 8

Mini Project: Library System - Part 8 (Streams & Reporting)

Rewrite all Library System catalog operations using the Stream API. Generate genre reports, find top-rated books, calculate statistics, export formatted reports with Collectors.joining, and build a composable BookFilter system.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Stream-Powered Library Analytics

Stream-Powered Library Analytics
import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class LibraryAnalytics {

    // Composable filter builder using lambda composition
    public static class BookQuery {
        private Predicate<Book> filter = book -> true;  // always-true default

        public BookQuery available()               { filter = filter.and(Book::isAvailable); return this; }
        public BookQuery byGenre(Genre g)          { filter = filter.and(b -> b.getGenre() == g); return this; }
        public BookQuery maxPrice(double max)      { filter = filter.and(b -> b.getPrice() <= max); return this; }
        public BookQuery byAuthor(String author)   { filter = filter.and(b -> b.getAuthor().equalsIgnoreCase(author)); return this; }
        public BookQuery titleContains(String kw)  { filter = filter.and(b -> b.getTitle().toLowerCase().contains(kw.toLowerCase())); return this; }

        public List<Book> execute(List<Book> catalog) {
            return catalog.stream().filter(filter).toList();
        }
    }

    public static void generateReport(List<Book> catalog) {
        System.out.println("\n╔══════════════════════════════════════╗");
        System.out.println("║         LIBRARY ANALYTICS REPORT    ║");
        System.out.println("╚══════════════════════════════════════╝");

        // Count & availability
        long total     = catalog.size();
        long available = catalog.stream().filter(Book::isAvailable).count();
        System.out.printf("Total books  : %d%n", total);
        System.out.printf("Available    : %d (%.0f%%)%n", available, (available * 100.0 / total));

        // Price statistics
        DoubleSummaryStatistics priceStats = catalog.stream()
            .mapToDouble(Book::getPrice).summaryStatistics();
        System.out.printf("Price range  : $%.2f - $%.2f (avg $%.2f)%n",
            priceStats.getMin(), priceStats.getMax(), priceStats.getAverage());

        // Total catalog value
        double totalValue = catalog.stream().mapToDouble(Book::getPrice).sum();
        System.out.printf("Total value  : $%.2f%n", totalValue);

        // Books per genre
        System.out.println("\n── Books per Genre ──");
        catalog.stream()
            .collect(Collectors.groupingBy(Book::getGenre, Collectors.counting()))
            .entrySet().stream()
            .sorted(Map.Entry.<Genre, Long>comparingByValue().reversed())
            .forEach(e -> System.out.printf("  %-20s %d%n", e.getKey().getDisplayName(), e.getValue()));

        // Top 3 most expensive available books
        System.out.println("\n── Top 3 Most Valuable Available Books ──");
        catalog.stream()
            .filter(Book::isAvailable)
            .sorted(Comparator.comparingDouble(Book::getPrice).reversed())
            .limit(3)
            .map(b -> String.format("  %-30s $%.2f", b.getTitle(), b.getPrice()))
            .forEach(System.out::println);

        // Authors with book counts
        System.out.println("\n── Authors ──");
        catalog.stream()
            .collect(Collectors.groupingBy(Book::getAuthor, Collectors.counting()))
            .entrySet().stream()
            .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
            .limit(5)
            .forEach(e -> System.out.printf("  %s (%d books)%n", e.getKey(), e.getValue()));

        // ISBN list (CSV)
        String isbnList = catalog.stream()
            .map(Book::getIsbn)
            .collect(Collectors.joining(", "));
        System.out.println("\n── All ISBNs ──\n  " + isbnList);
    }

    public static void main(String[] args) {
        List<Book> catalog = List.of(
            new Book("001", "Clean Code", "Robert Martin", 39.99),
            new Book("002", "Effective Java", "Joshua Bloch", 44.99),
            new Book("003", "DDIA", "Martin Kleppmann", 49.99)
        );

        // Composable query
        List<Book> picks = new BookQuery()
            .available()
            .maxPrice(50.0)
            .execute(catalog);
        picks.forEach(b -> System.out.println(b.getTitle()));

        generateReport(catalog);
    }
}

Quick Quiz

Tip

Tip

Practice Mini Project Library System Part 8 Streams Reporting in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Library System - Part 8 (Streams & Reporting)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Library System Part 8 Streams Reporting from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Mini Project Library System Part 8 Streams Reporting is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done