Java 17: Sum all numbers in a nested, mixed-type structure. Compare casts, pattern matching, streams and an iterative stack.
Problem
Given List<Object> containing Integer, Double, numeric Strings, nested Lists and Maps (sum their values), return the total. It tests type checks, recursion, and pattern matching for instanceof (Java 16+).
Approach 1: Java 8 instanceof with casts (recursive)
import java.util.Collection;
import java.util.Map;
class NestedSumJava8 {
static double sum(Object node) {
if (node instanceof Number) {
return ((Number) node).doubleValue();
} else if (node instanceof String) {
String s = (String) node;
return s.matches("-?\\d+(\\.\\d+)?") ? Double.parseDouble(s) : 0;
} else if (node instanceof Collection) {
double total = 0;
for (Object child : (Collection<?>) node) total += sum(child);
return total;
} else if (node instanceof Map) {
return sum(((Map<?, ?>) node).values());
}
return 0;
}
}Approach 2: Pattern matching for instanceof (Java 16+)
Test and bind in one expression; conditions can use the bound variable in the same && chain.
import java.util.Collection;
import java.util.Map;
class NestedSumPatterns {
static double sum(Object node) {
if (node instanceof Number n) return n.doubleValue();
if (node instanceof String s && s.matches("-?\\d+(\\.\\d+)?")) return Double.parseDouble(s);
if (node instanceof Collection<?> c) {
double total = 0;
for (Object child : c) total += sum(child);
return total;
}
if (node instanceof Map<?, ?> m) return sum(m.values());
return 0; // non-numeric strings, nulls, other types
}
}Approach 3: Recursive stream flattening (functional style)
Flatten the tree into a stream of leaves with flatMap, then sum. Elegant; allocates a stream per container.
import java.util.Collection;
import java.util.Map;
import java.util.stream.Stream;
class NestedSumStreams {
static Stream<Object> leaves(Object node) {
if (node instanceof Collection<?> c) return c.stream().flatMap(NestedSumStreams::leaves);
if (node instanceof Map<?, ?> m) return m.values().stream().flatMap(NestedSumStreams::leaves);
return Stream.of(node);
}
static double sum(Object root) {
return leaves(root).mapToDouble(NestedSumPatterns::sum).sum(); // reuse the leaf rules
}
}Approach 4: Iterative with an explicit stack (optimal robustness)
Recursion depth equals nesting depth, so a deeply nested input (malicious JSON, for example) can cause StackOverflowError. An ArrayDeque moves the stack to the heap. Same O(total elements) time.
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.Map;
class NestedSumIterative {
static double sum(Object root) {
Deque<Object> stack = new ArrayDeque<>();
if (root != null) stack.push(root);
double total = 0;
while (!stack.isEmpty()) {
Object node = stack.pop();
if (node instanceof Collection<?> c) { for (Object child : c) if (child != null) stack.push(child); }
else if (node instanceof Map<?, ?> m) { for (Object v : m.values()) if (v != null) stack.push(v); }
else total += NestedSumPatterns.sum(node);
}
return total;
}
}
class NestedSumDemo {
public static void main(String[] args) {
Object data = java.util.List.of(1, 2.5, "3", "abc", java.util.List.of(4, java.util.List.of("5.5", 6)),
java.util.Map.of("a", 7, "b", java.util.List.of(8)));
System.out.println(NestedSumJava8.sum(data) + " " + NestedSumPatterns.sum(data) + " "
+ NestedSumStreams.sum(data) + " " + NestedSumIterative.sum(data)); // 37.0 x4
Object deep = 1;
for (int i = 0; i < 100_000; i++) deep = java.util.List.of(deep); // 100k levels deep
System.out.println(NestedSumIterative.sum(deep)); // 1.0
try { NestedSumPatterns.sum(deep); } catch (StackOverflowError e) { System.out.println("recursive version: StackOverflowError"); }
}
}Feasible → optimal
All are O(n) in the number of elements. Pattern matching makes the type checks concise and cast-free; the iterative stack is the most robust for untrusted or very deep input. In Java 21, a pattern switch (case Number n ->, case String s when ... ->) expresses the same dispatch even more compactly.
Follow-up questions interviewers ask
Try answering each one before you open it.
What is the scope of a pattern variable like `s` in `node instanceof String s && s.isEmpty()`?
It is in scope wherever the compiler can prove the match succeeded ("flow scoping"): in the rest of an && chain and in the if body, but not after ||. With a negated test, if (!(o instanceof String s)) return;, s is in scope after the if, which is handy for guard clauses.
Why use `Collection<?>` rather than `Collection<Object>` in the pattern?
Generic type arguments are erased at runtime, so the JVM can only check the raw type. instanceof Collection<?> is always safe; instanceof Collection<Object> would be rejected (unchecked) unless the static type already guarantees it.