KatInterview

Thread-Safe Maps and Stream Collectors in Java

BehavioralModel answer
MediumModel answerBehavioraljavaconcurrencystreams

Last updated

Compare Java's concurrent map implementations and write a Stream-based method to find the highest-value transaction per trader.

Part 1: Thread-Safe Map Implementations

Compare two approaches to thread-safe maps in Java: ConcurrentHashMap and wrapping a HashMap with Collections.synchronizedMap(). Your answer should cover:

  • How each approach implements synchronization and what this means for concurrent access patterns
  • The behavior of their iterators when the map is modified during iteration
  • Trade-offs in performance and safety

Part 2: Finding Maximum Transactions with Streams

Given a list of Transaction objects where each has:

  • String traderId — identifier for the trader
  • int amount — transaction value
  • String currency — currency code

Implement a method using Java Streams that produces a Map<String, Optional<Transaction>>. The map should associate each trader ID with an Optional holding their highest-amount transaction.

class Transaction {
    String traderId;
    int amount;
    String currency;
    // Constructor and getters provided
}

Requirements:

  • Use Collectors.groupingBy for partitioning by trader
  • Use Collectors.maxBy to identify the largest transaction
  • Handle empty inputs without errors

Sample Input:

[Transaction("trader1", 150, "USD"), 
 Transaction("trader1", 300, "USD"), 
 Transaction("trader2", 75, "EUR")]

Expected Output:

{"trader1": Optional[Transaction("trader1", 300, "USD")], 
 "trader2": Optional[Transaction("trader2", 75, "EUR")]}

Hints

Hint 1

For Part 1: think about whether locks are per-map or per-bucket, and whether iteration requires external locking

Hint 2

For Part 2: the downstream collector in groupingBy will run separately for each trader's transactions

Hint 3

Consider what happens with null values in both the concurrent map and the stream pipeline