Search⌘ K
AI Features

Solution: The Expired Product Purge

Explore how to effectively purge expired or zero-stock products from a collection by iterating safely using Java's Iterator. Understand the use of string splitting, parsing, and business logic checks to manage product data without runtime errors or data corruption.

We'll cover the following...
Java 25
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class WarehouseManager {
static class Product {
String name;
int stock;
String status;
public Product(String name, int stock, String status) {
this.name = name;
this.stock = stock;
this.status = status;
}
@Override
public String toString() {
return name + " (Stock: " + stock + ", Status: " + status + ")";
}
}
public static List<Product> loadProducts(String filePath) {
List<Product> products = new ArrayList<>();
try {
List<String> lines = Files.readAllLines(Path.of(filePath));
// Start loop at 1 to skip the CSV header row
for (int i = 1; i < lines.size(); i++) {
String line = lines.get(i);
String[] parts = line.split(",");
// Parse CSV columns
String name = parts[0].trim();
int stock = Integer.parseInt(parts[1].trim());
String status = parts[2].trim();
products.add(new Product(name, stock, status));
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
return products;
}
public static void removeUnsellableItems(List<Product> inventory) {
Iterator<Product> it = inventory.iterator();
while (it.hasNext()) {
Product p = it.next();
// Remove if Stock is 0 OR Status is Expired
if (p.stock == 0 || p.status.equals("Expired")) {
it.remove();
}
}
}
public static void main(String[] args) {
System.out.println("--- Loading Inventory ---");
List<Product> inventory = loadProducts(filePath);
System.out.println("Loaded " + inventory.size() + " items.");
// Print first 5 to verify loading
if (!inventory.isEmpty()) {
System.out.println("First 5 items: " + inventory.subList(0, Math.min(inventory.size(), 5)));
}
System.out.println("\n--- Purging Unsellable Items ---");
removeUnsellableItems(inventory);
System.out.println("Purge complete.");
System.out.println("Remaining items: " + inventory.size());
System.out.println("Active Inventory:");
for (Product p : inventory) {
System.out.println(" - " + p);
}
}
}
...