// CollectionsDemo.java — List, Set, Map and iterating safely.
import java.util.*;

public class CollectionsDemo {

    public static void main(String[] args) {
        // List: ordered, allows duplicates
        List<String> skus = new ArrayList<>();
        skus.add("AX-200");
        skus.add("BX-310");
        skus.add("AX-200");
        System.out.println(skus + " size=" + skus.size());   // [AX-200, BX-310, AX-200] size=3
        System.out.println("First: " + skus.get(0));

        // Set: no duplicates
        Set<String> unique = new HashSet<>(skus);
        System.out.println("Unique count: " + unique.size());  // 2

        // TreeSet keeps items sorted
        Set<String> sorted = new TreeSet<>(List.of("pear", "apple", "fig"));
        System.out.println(sorted);                            // [apple, fig, pear]

        // Map: key -> value
        Map<String, Integer> stock = new HashMap<>();
        stock.put("AX-200", 12);
        stock.put("BX-310", 0);
        stock.merge("AX-200", 5, Integer::sum);                // add 5 to existing value
        System.out.println("AX-200 stock: " + stock.get("AX-200"));               // 17
        System.out.println("CX-420 stock: " + stock.getOrDefault("CX-420", 0));    // 0

        for (Map.Entry<String, Integer> e : new TreeMap<>(stock).entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
        }

        // Immutable collections (Java 9+)
        List<Integer> fixed = List.of(1, 2, 3);
        try {
            fixed.add(4);
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of(...) cannot be changed");
        }

        // Remove while iterating: use removeIf (not a for-each loop)
        List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        numbers.removeIf(n -> n % 2 == 0);
        System.out.println(numbers);                           // [1, 3, 5]

        // Sorting
        List<String> names = new ArrayList<>(List.of("Globex", "acme", "Initech"));
        names.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println(names);                             // [acme, Globex, Initech]
    }
}
