Topological Sort Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Topological Sort runs in O(V+E) time and O(V) space, in Java as in every other language.
- ✓java.util.ArrayDeque as the queue (Oracle's own Javadoc recommends it over both Stack and LinkedList for stack and queue use), and java.util.PriorityQueue<T> with a Comparator when the ordering must be canonical rather than merely valid.
- ✓ArrayDeque, not LinkedList and not the legacy Stack class, this is close to a mechanical rule in Java code review at this point, because both alternatives carry real, well-documented cost (see pitfall) that ArrayDeque simply does not have.
- ✓The Java trap: java.util.Stack extends the legacy Vector class, which synchronizes every single method, even in single-threaded code, every push and pop pays uncontended lock-acquisition overhead for no benefit, and LinkedList, while unsynchronized, allocates a separate Node object with two pointers for every element, far more allocation and far worse cache locality than ArrayDeque's contiguous backing array.
- ✓O(V+E) with ArrayDeque, whose array-backed ring buffer gives O(1) amortized offer/poll with good cache locality; PriorityQueue's offer and poll are O(log n), so the canonical-ordering variant is O((V+E) log V), a genuine complexity difference, not a constant-factor one, exactly like Rust's BinaryHeap case, because a binary heap fundamentally cannot beat O(log n) per operation.
What Topological Sort actually is
Topological Sort in Java: what you actually reach for
Java implementation
import java.util.*;
class TopoSort {
static List<Integer> order(Map<Integer, List<Integer>> graph) {
Map<Integer, Integer> indegree = new HashMap<>();
for (int node : graph.keySet()) indegree.putIfAbsent(node, 0);
for (var entry : graph.entrySet()) {
for (int next : entry.getValue()) {
indegree.merge(next, 1, Integer::sum);
}
}
Deque<Integer> queue = new ArrayDeque<>(); // ArrayDeque, not LinkedList/Stack (both legacy-discouraged)
indegree.forEach((node, d) -> { if (d == 0) queue.add(node); });
List<Integer> order = new ArrayList<>(indegree.size());
while (!queue.isEmpty()) {
int node = queue.poll();
order.add(node);
for (int next : graph.getOrDefault(node, List.of())) {
int d = indegree.merge(next, -1, Integer::sum);
if (d == 0) queue.add(next);
}
}
if (order.size() != indegree.size()) {
throw new IllegalStateException("not a DAG: cycle present");
}
return order;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(V+E)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Topological Sort?
java.util.ArrayDeque as the queue (Oracle's own Javadoc recommends it over both Stack and LinkedList for stack and queue use), and java.util.PriorityQueue<T> with a Comparator when the ordering must be canonical rather than merely valid.
What is the most common Java mistake when implementing Topological Sort?
java.util.Stack extends the legacy Vector class, which synchronizes every single method, even in single-threaded code, every push and pop pays uncontended lock-acquisition overhead for no benefit, and LinkedList, while unsynchronized, allocates a separate Node object with two pointers for every element, far more allocation and far worse cache locality than ArrayDeque's contiguous backing array. Both compile fine and produce correct output; the cost only shows up as a measurable slowdown at scale, exactly why this is treated as a code-review-level idiom rule rather than something the compiler catches.
How does Topological Sort actually perform in Java?
O(V+E) with ArrayDeque, whose array-backed ring buffer gives O(1) amortized offer/poll with good cache locality; PriorityQueue's offer and poll are O(log n), so the canonical-ordering variant is O((V+E) log V), a genuine complexity difference, not a constant-factor one, exactly like Rust's BinaryHeap case, because a binary heap fundamentally cannot beat O(log n) per operation. Time complexity is O(V+E) and space is O(V).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.