LearnFrenzy
Sign in Take a free test

Collections Framework · Collections Programs · Question 8

Sort an inventory list several ways in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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());
    }
}

Output Verified by compiling and running

Electronics  Mouse       699
Electronics  Keyboard   1499
Electronics  Monitor    9999
Stationery   Pen          20
Stationery   Notebook     60
Stationery   Stapler     150
low stock: [Monitor(6), Notebook(8), Stapler(3)]
top 3: [Monitor, Keyboard, Mouse]

One list, several Comparators; subList(0, 3) takes the first three after sorting.

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