ItTechGenie-Subject - Java Collections (Warm-up + 10 Questions)

Java Question Bank

Java Collections | Q0 Warm‑up (Show/Hide Answer) + Q1–Q10 Scenario Questions (5 Moderate + 5 Complex) — With Answers

Instruction: Full boilerplate is visible by default. Students implement ONLY methods/members marked // ✅ TODO.
Answers: Q0 and Q1–Q10 include answers (logic + code) behind Show/Hide Answer.
Warm‑up: 1 (Q0) Moderate: 5 (Q1–Q5) Complex: 5 (Q6–Q10) Sample Inputs: spaces + quotes + unicode α/β + emoji ✅ + special chars
0

Warm‑up: Pick the right Collection (with answer)

ListSetMapQueueWarm-up

Warm‑up (with answer): You receive a list of "orders" as strings. You must choose the BEST Java Collection for each need: 1) Preserve insertion order and allow duplicates 2) Fast membership check (unique) 3) Sorted unique view (ascending) 4) Key->Value mapping (look up by id) 5) FIFO processing Print 5 lines: requirement -> collection + reason (1 short line each).

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                          // Collections

public class Main {                                                   // entry class
    // ✅ TODO: Student must implement only this method
    static void mapNeedsToCollections() {
        // TODO:
        // - Print 5 lines mapping requirement -> best collection + reason
        // - Examples: ArrayList, HashSet, TreeSet, HashMap, ArrayDeque
        throw new UnsupportedOperationException("TODO");
    }

    public static void main(String[] args) {
        mapNeedsToCollections();                                      // run warm-up
    }
}

Warm‑up Answer (Mappings)

Typical mapping: 1) insertion order + duplicates => ArrayList (keeps order, allows duplicates) 2) fast membership + unique => HashSet (O(1) average contains) 3) sorted unique => TreeSet (sorted + unique) 4) key->value => HashMap (fast lookup by key) 5) FIFO => ArrayDeque (queue operations add/remove)

System.out.println("1) Order+duplicates => ArrayList (keeps insertion order, duplicates allowed).");
System.out.println("2) Fast unique contains => HashSet (avg O(1) membership).");
System.out.println("3) Sorted unique => TreeSet (sorted + unique elements).");
System.out.println("4) Key->Value lookup => HashMap (fast key lookup).");
System.out.println("5) FIFO processing => ArrayDeque (queue operations).");
1

Log Sanitizer — List + Filtering

ArrayListString ParsingFilteringModerate

Scenario: You receive raw log lines (with quotes, emojis, special chars). You must: - split by newline - trim each line - keep only lines that contain "ERROR" (case-insensitive) - return as List<String> preserving original order Implement ONLY TODO: - LogSanitizer.extractErrors(String raw) Print the resulting list.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // List

class LogSanitizer {
    // ✅ TODO: Student must implement only this method
    static List<String> extractErrors(String raw) {
        // TODO:
        // - split by \n
        // - trim lines, ignore empty
        // - if line contains "ERROR" ignoring case => add to list
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        String raw = "INFO  \"login ok\"  user=Gopi ✅\n"
                   + "error  \"db timeout\"  id=α1 !@#\n"
                   + "WARN  \"retry\"  ✅\n"
                   + "ERROR \"payment failed\" order=\"ORD-β2\" 💥\n";

        System.out.println(LogSanitizer.extractErrors(raw));          // print list
    }
}

Answer (Logic + Code)

Use ArrayList to preserve order; parse lines safely; case-insensitive contains check.

static List<String> extractErrors(String raw) {
    List<String> out = new ArrayList<>();
    if (raw == null) return out;

    String[] lines = raw.split("\n");
    for (String line : lines) {
        if (line == null) continue;
        String t = line.trim();
        if (t.isEmpty()) continue;
        if (t.toUpperCase().contains("ERROR")) out.add(t);
    }
    return out;
}
2

Coupon Deduplicator — Set + Normalization

HashSetUniquenessNormalizationModerate

Scenario: You receive coupon codes separated by commas. Rules: - trim - remove surrounding quotes - treat codes case-insensitively - output unique set count and set Implement ONLY TODO: - CouponService.uniqueCoupons(String csv) Print: count + set.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // Set

class CouponService {
    // ✅ TODO: Student must implement only this method
    static Set<String> uniqueCoupons(String csv) {
        // TODO:
        // - split by comma
        // - normalize: trim, remove quotes, uppercase
        // - ignore empty or non-alphanumeric codes
        // - store in HashSet
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        String csv = " \"SAVE10\" , save10 ✅ ,  \"FREESHIP\"  , freeShip ,  \"\" ,  !@#  ";
        Set<String> set = CouponService.uniqueCoupons(csv);
        System.out.println(set.size());
        System.out.println(set);
    }
}

Answer (Logic + Code)

HashSet ensures uniqueness; normalize to uppercase; ignore invalid tokens.

static Set<String> uniqueCoupons(String csv) {
    Set<String> set = new HashSet<>();
    if (csv == null) return set;

    String[] parts = csv.split(",");
    for (String p : parts) {
        String t = (p == null ? "" : p.trim());
        t = t.replace(""", "");                                     // remove quotes
        t = t.replace("✅", "").trim();                                // remove marker
        if (t.isEmpty()) continue;

        // keep only letters+digits
        boolean ok = true;
        for (int i = 0; i < t.length(); i++) {
            char ch = t.charAt(i);
            if (!Character.isLetterOrDigit(ch)) { ok = false; break; }
        }
        if (!ok) continue;

        set.add(t.toUpperCase());
    }
    return set;
}
3

Word Counter — Map Frequency

HashMapAggregationText ProcessingModerate

Scenario: You receive a sentence with punctuation and unicode. Count word frequency (case-insensitive), ignoring empty and punctuation. Return Map<String,Integer>. Implement ONLY TODO: - WordCounter.countWords(String text) Print top 3 entries (any order ok).

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // Map

class WordCounter {
    // ✅ TODO: Student must implement only this method
    static Map<String,Integer> countWords(String text) {
        // TODO:
        // - split by non-letter/digit (regex)
        // - normalize to lower-case
        // - increment counts in HashMap
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        Map<String,Integer> m = WordCounter.countWords("Hello, hello ✅ world! α/β world... 'world' 😄 @@@");
        System.out.println(m);
    }
}

Answer (Logic + Code)

HashMap for frequency; regex split removes punctuation; normalize for case-insensitivity.

static Map<String,Integer> countWords(String text) {
    Map<String,Integer> m = new HashMap<>();
    if (text == null) return m;

    String cleaned = text.replace("✅", "");                           // remove marker
    String[] tokens = cleaned.split("[^\p{L}\p{N}]+");              // letters/numbers unicode-aware
    for (String tok : tokens) {
        if (tok == null) continue;
        String w = tok.trim().toLowerCase();
        if (w.isEmpty()) continue;
        m.put(w, m.getOrDefault(w, 0) + 1);
    }
    return m;
}
4

Support Queue — FIFO with ArrayDeque

QueueArrayDequeFIFOModerate

Scenario: Support tickets arrive as strings. Process them FIFO: - enqueue tickets (ignore empty) - process N tickets (poll) - return processed list Implement ONLY TODO: - SupportQueue.process(String[] tickets, int n) Print processed list + remaining size.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // Deque

class SupportQueue {
    // ✅ TODO: Student must implement only this method
    static List<String> process(String[] tickets, int n) {
        // TODO:
        // - use ArrayDeque as queue
        // - offer trimmed non-empty tickets
        // - poll up to n tickets; store into ArrayList in order
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        String[] tickets = {"  TKT-1 ✅  ", "", "TKT-2 \"urgent\"", "TKT-α3!@#", "  "};
        List<String> processed = SupportQueue.process(tickets, 3);
        System.out.println(processed);
    }
}

Answer (Logic + Code)

ArrayDeque provides fast FIFO operations; keep order; poll up to N.

static List<String> process(String[] tickets, int n) {
    Deque<String> q = new ArrayDeque<>();
    if (tickets != null) {
        for (String t : tickets) {
            String x = (t == null ? "" : t.trim());
            x = x.replace("✅", "").trim();
            if (!x.isEmpty()) q.offer(x);
        }
    }

    List<String> done = new ArrayList<>();
    for (int i = 0; i < n && !q.isEmpty(); i++) {
        done.add(q.poll());
    }
    return done;
}
5

Leaderboard — Sort List of Players

ComparatorSortingListModerate

Scenario: Players have name + score. Sort descending by score, then ascending by name (case-insensitive). Implement ONLY TODO: - Leaderboard.sort(List<Player> list) Print sorted players.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // List, Comparator

class Player {
    final String name;                                               // immutable name
    final int score;                                                 // immutable score
    Player(String name, int score){ this.name = name; this.score = score; }
    public String toString(){ return name + ":" + score; }           // print helper
}

class Leaderboard {
    // ✅ TODO: Student must implement only this method
    static void sort(List<Player> list) {
        // TODO:
        // - sort by score DESC then name ASC (case-insensitive)
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        List<Player> list = new ArrayList<>();
        list.add(new Player("Gopi ✅", 90));
        list.add(new Player("Aryan", 90));
        list.add(new Player("βeta", 120));
        list.add(new Player("gopi", 75));
        list.add(new Player("Zed!@#", 120));

        Leaderboard.sort(list);
        System.out.println(list);
    }
}

Answer (Logic + Code)

Use Collections.sort with Comparator chain; score desc then name asc ignoring case.

static void sort(List<Player> list) {
    if (list == null) return;
    list.sort((a,b) -> {
        int sc = Integer.compare(b.score, a.score);                   // desc
        if (sc != 0) return sc;
        String an = (a.name == null ? "" : a.name.replace("✅","").trim());
        String bn = (b.name == null ? "" : b.name.replace("✅","").trim());
        return an.compareToIgnoreCase(bn);                             // asc
    });
}
6

LRU Cache — LinkedHashMap (Access Order)

LinkedHashMapLRUO(1) cacheComplex

Scenario: Build an LRU cache for product lookups. Requirements: - capacity fixed - on get(key): return value and mark as recently used - on put(key,val): insert/update; if size exceeds capacity, evict least recently used Implement ONLY TODO: - LruCache constructor (set accessOrder=true) - removeEldestEntry logic Test using simple puts/gets in main.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // LinkedHashMap

class LruCache<K,V> extends LinkedHashMap<K,V> {
    private final int capacity;

    // ✅ TODO: Student must implement only this constructor
    LruCache(int capacity) {
        // TODO:
        // - call super(initialCapacity, loadFactor, accessOrder=true)
        // - store capacity
        throw new UnsupportedOperationException("TODO");
    }

    // ✅ TODO: Student must implement only this method
    @Override
    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        // TODO:
        // - return true when size() > capacity
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        LruCache<String,String> c = new LruCache<>(2);
        c.put("p:α1 ✅","Phone");
        c.put("p:β2","Laptop");
        c.get("p:α1 ✅");                                             // make α1 most recent
        c.put("p:γ3!@#","Tablet");                                     // should evict β2
        System.out.println(c);
    }
}

Answer (Logic + Code)

LinkedHashMap with accessOrder=true provides LRU behavior; removeEldestEntry enforces capacity.

LruCache(int capacity) {
    super(16, 0.75f, true);                                           // accessOrder=true
    this.capacity = capacity;
}

@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
    return size() > capacity;                                         // evict when exceeded
}
7

Group Orders — Map of Lists (Multimap)

MapGroupingCollectionsComplex

Scenario: You receive order lines: "region|orderId|amount". Group orderIds by region preserving insertion order per region. Implement ONLY TODO: - OrderGrouper.groupByRegion(List<String> lines) Requirements: - normalize region: trim + uppercase - ignore invalid lines - use LinkedHashMap to keep region order of first appearance Print the resulting map.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // Map, List

class OrderGrouper {
    // ✅ TODO: Student must implement only this method
    static Map<String, List<String>> groupByRegion(List<String> lines) {
        // TODO:
        // - LinkedHashMap<String, List<String>>
        // - parse by '|'
        // - add orderId into map.get(region)
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        List<String> lines = Arrays.asList(
            " South | ORD-α1 ✅ | 1200 ",
            " North| ORD-β2 | 900 ",
            " south| ORD-γ3!@# | 500 ",
            "  | bad | line ",
            " East | ORD-δ4 \"rush\" | 700 "
        );

        System.out.println(OrderGrouper.groupByRegion(lines));
    }
}

Answer (Logic + Code)

Use LinkedHashMap to preserve region appearance order; store values in ArrayList per key; validate parsing.

static Map<String, List<String>> groupByRegion(List<String> lines) {
    Map<String, List<String>> map = new LinkedHashMap<>();
    if (lines == null) return map;

    for (String line : lines) {
        if (line == null) continue;
        String[] parts = line.split("\\|");
        if (parts.length < 2) continue;

        String region = parts[0].trim().toUpperCase();
        String orderId = parts[1].trim().replace("✅","").trim();

        if (region.isEmpty() || orderId.isEmpty()) continue;

        map.computeIfAbsent(region, k -> new ArrayList<>()).add(orderId);
    }
    return map;
}
8

Top-K Products — PriorityQueue

PriorityQueueTop-KComparatorComplex

Scenario: You receive product sales as "id:count". Find top K products by count descending. If tie, smaller id (lexicographic) first. Implement ONLY TODO: - TopK.topK(Map<String,Integer> sales, int k) Return List<String> of ids sorted by desired final order. Hint: - Use PriorityQueue with custom comparator (min-heap) to keep size K. - Then reverse at end. Print output.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;                                               // PQ, Map

class TopK {
    // ✅ TODO: Student must implement only this method
    static List<String> topK(Map<String,Integer> sales, int k) {
        // TODO:
        // - priority queue keeps worst at head
        // - compare by count ASC; if tie, id DESC (so worse ties pop)
        // - push entries, if size > k => poll
        // - collect ids and reverse by best order (count desc, id asc)
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        Map<String,Integer> sales = new HashMap<>();
        sales.put("p-α1 ✅", 120);
        sales.put("p-β2", 120);
        sales.put("p-γ3!@#", 50);
        sales.put("p-δ4", 75);
        sales.put("p-ε5", 200);

        System.out.println(TopK.topK(sales, 3));
    }
}

Answer (Logic + Code)

PriorityQueue for streaming top-K; keep min-heap of size K; comparator decides which element is 'worst'.

static List<String> topK(Map<String,Integer> sales, int k) {
    if (sales == null || k <= 0) return new ArrayList<>();

    Comparator<Map.Entry<String,Integer>> worstFirst = (a,b) -> {
        int c = Integer.compare(a.getValue(), b.getValue());          // count asc => worse first
        if (c != 0) return c;
        return a.getKey().compareTo(b.getKey());                      // id asc (we'll invert below)
    };

    // For tie-handling in min-heap, make "worse" be larger id
    worstFirst = (a,b) -> {
        int c = Integer.compare(a.getValue(), b.getValue());
        if (c != 0) return c;
        return b.getKey().compareTo(a.getKey());                      // id desc => worse first
    };

    PriorityQueue<Map.Entry<String,Integer>> pq = new PriorityQueue<>(worstFirst);

    for (Map.Entry<String,Integer> e : sales.entrySet()) {
        pq.offer(e);
        if (pq.size() > k) pq.poll();
    }

    List<Map.Entry<String,Integer>> tmp = new ArrayList<>();
    while (!pq.isEmpty()) tmp.add(pq.poll());

    // sort final best-first: count desc, id asc
    tmp.sort((a,b) -> {
        int c = Integer.compare(b.getValue(), a.getValue());
        if (c != 0) return c;
        return a.getKey().compareTo(b.getKey());
    });

    List<String> out = new ArrayList<>();
    for (Map.Entry<String,Integer> e : tmp) out.add(e.getKey());
    return out;
}
9

Cleanup Blocklist — Iterator Safe Remove

IteratorConcurrentModificationListComplex

Scenario: You maintain a mutable list of blocked usernames. Remove users whose name length < 3 OR contains any non-letter/digit. You MUST remove safely without ConcurrentModificationException. Implement ONLY TODO: - BlocklistCleaner.clean(List<String> users) Print cleaned list.

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;

class BlocklistCleaner {
    // ✅ TODO: Student must implement only this method
    static void clean(List<String> users) {
        // TODO:
        // - iterate with Iterator and remove()
        // - invalid if length < 3 OR contains non-letter/digit (after removing ✅)
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        List<String> users = new ArrayList<>(Arrays.asList("ab", "gopi✅", "A_ryan", "βeta", "ok", "User123", "!!bad!!"));
        BlocklistCleaner.clean(users);
        System.out.println(users);
    }
}

Answer (Logic + Code)

Use Iterator.remove() to avoid ConcurrentModificationException; validate with Character checks.

static void clean(List<String> users) {
    if (users == null) return;

    Iterator<String> it = users.iterator();
    while (it.hasNext()) {
        String u = it.next();
        String t = (u == null ? "" : u.replace("✅","").trim());

        if (t.length() < 3) { it.remove(); continue; }

        boolean ok = true;
        for (int i = 0; i < t.length(); i++) {
            if (!Character.isLetterOrDigit(t.charAt(i))) { ok = false; break; }
        }
        if (!ok) it.remove();
    }
}
10

Inventory Merge — Map Merge + Snapshot

Map.mergecomputeIfAbsentImmutable SnapshotComplex

Scenario: You receive two inventories (sku -> qty). Merge them: - qty = qtyA + qtyB - if key missing, treat as 0 Then produce an immutable snapshot Map (unmodifiable) to return to caller. Implement ONLY TODO: - InventoryMerger.mergeAndFreeze(Map<String,Integer> a, Map<String,Integer> b) Print merged map and attempt to modify it (should throw UnsupportedOperationException).

✅ Sample input includes spaces, quotes, unicode α/β, emoji ✅, and special chars to test parsing and edge cases.
Java Collections scenario (students implement ONLY TODO methods) Ctrl+C
import java.util.*;

class InventoryMerger {
    // ✅ TODO: Student must implement only this method
    static Map<String,Integer> mergeAndFreeze(Map<String,Integer> a, Map<String,Integer> b) {
        // TODO:
        // - create new HashMap result
        // - add all from a
        // - for each entry in b: result.merge(key, val, Integer::sum)
        // - return Collections.unmodifiableMap(result)
        throw new UnsupportedOperationException("TODO");
    }
}

public class Main {
    public static void main(String[] args) {
        Map<String,Integer> a = new HashMap<>();
        a.put("SKU-α1 ✅", 10);
        a.put("SKU-β2", 5);

        Map<String,Integer> b = new HashMap<>();
        b.put("SKU-β2", 7);
        b.put("SKU-γ3!@#", 3);

        Map<String,Integer> merged = InventoryMerger.mergeAndFreeze(a,b);
        System.out.println(merged);

        // merged.put("X", 1); // should throw if uncommented
    }
}

Answer (Logic + Code)

Use Map.merge for concise aggregation; return unmodifiable map to protect snapshot from modifications.

static Map<String,Integer> mergeAndFreeze(Map<String,Integer> a, Map<String,Integer> b) {
    Map<String,Integer> res = new HashMap<>();

    if (a != null) {
        for (Map.Entry<String,Integer> e : a.entrySet()) {
            res.put(e.getKey(), e.getValue());
        }
    }

    if (b != null) {
        for (Map.Entry<String,Integer> e : b.entrySet()) {
            res.merge(e.getKey(), e.getValue(), Integer::sum);
        }
    }

    return Collections.unmodifiableMap(res);
}