Store Item records (name, category, price, stock) in a List and print: all items by category then price, items with low stock (< 10), and the three most expensive items.
Solution
Main.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
record Item(String name, String category, int price, int stock) { }
public class Main {
public static void main(String[] args) {
List<Item> items = new ArrayList<>(List.of(
new Item("Mouse", "Electronics", 699, 40), new Item("Pen", "Stationery", 20, 500),
new Item("Monitor", "Electronics", 9999, 6), new Item("Notebook", "Stationery", 60, 8),
new Item("Keyboard", "Electronics", 1499, 12), new Item("Stapler", "Stationery", 150, 3)));
items.sort(Comparator.comparing(Item::category).thenComparingInt(Item::price));
items.forEach(i -> System.out.printf("%-12s %-9s %5d%n", i.category(), i.name(), i.price()));
List<String> low = new ArrayList<>();
for (Item i : items) if (i.stock() < 10) low.add(i.name() + "(" + i.stock() + ")");
System.out.println("low stock: " + low);
List<Item> byPrice = new ArrayList<>(items);
byPrice.sort(Comparator.comparingInt(Item::price).reversed());
System.out.println("top 3: " + byPrice.subList(0, 3).stream().map(Item::name).toList());
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!