Inventory Report
Completed
Read products name category qty price. Print, per category (sorted), the number of products and the stock value (2 decimals), then the overall most valuable product. Use streams with groupingBy.
Input
n, then n lines.
Output
One line per category, then top: NAME VALUE.
Example
Input
4 pen office 100 1.5 desk office 2 120 apple food 50 0.4 laptop tech 3 899.99
Output
food 1 20.00 office 2 390.00 tech 1 2699.97 top: laptop 2699.97
Editor
Java
Hints
groupingBy into a TreeMap keeps categories sorted.
max(Comparator) returns an Optional - call get() when you know the list isn't empty.
Solution explanation
Streams turn a reporting task into a few declarative steps.
Show solution
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.stream.Collectors;
class Product {
final String name, category;
final int qty;
final double price;
Product(String name, String category, int qty, double price) {
this.name = name;
this.category = category;
this.qty = qty;
this.price = price;
}
double value() {
return qty * price;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Product> products = new ArrayList<>();
for (int i = 0; i < n; i++) {
products.add(new Product(sc.next(), sc.next(), sc.nextInt(), sc.nextDouble()));
}
Map<String, List<Product>> byCategory = products.stream()
.collect(Collectors.groupingBy(p -> p.category, TreeMap::new, Collectors.toList()));
byCategory.forEach((cat, list) -> System.out.printf("%s %d %.2f%n", cat, list.size(),
list.stream().mapToDouble(Product::value).sum()));
Product top = products.stream().max(Comparator.comparingDouble(Product::value)).get();
System.out.printf("top: %s %.2f%n", top.name, top.value());
}
}