Q1.Use streams to group test results by status and count them.
Short answer: Collectors.groupingBy with Collectors.counting(). Interviewers at this level want to see you can read and write this without a loop.
record Result(String name, String status) {}
List<Result> results = List.of(
new Result("login", "PASS"), new Result("search", "FAIL"),
new Result("cart", "PASS"), new Result("pay", "SKIP"));
Map<String, Long> byStatus = results.stream()
.collect(Collectors.groupingBy(Result::status, TreeMap::new, Collectors.counting()));
System.out.println(byStatus); // {FAIL=1, PASS=2, SKIP=1}
The TreeMap::new argument sorts the keys so the output is stable - useful when you assert on it.
- Using parallelStream() for small lists - it adds overhead and gives no benefit
- How would you get the names of failed tests only?
- What does Collectors.partitioningBy return?
