Huffman Encoding 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
- ✓Huffman Encoding runs in O(n log n) time and O(n) space, in Java as in every other language.
- ✓java.util.PriorityQueue<E> is a genuine binary min-heap out of the box, unlike Go, no adapter is needed, only a Comparator (or a natural Comparable ordering on the element type) to define priority.
- ✓Declare `sealed interface HuffNode permits Leaf, Internal {}` with `record Leaf(int weight, char symbol) implements HuffNode {}` and `record Internal(int weight, HuffNode left, HuffNode right) implements HuffNode {}`, then use a pattern-matching switch expression that the compiler flags as incomplete if a third permitted type is ever added.
- ✓The Java trap: PriorityQueue's iteration order is NOT sorted order, only poll() and peek() respect priority; iterating the queue directly (for-each, or passing it to a stream) yields elements in the internal heap-array order, which looks almost-sorted for small inputs and misleads people into believing they can inspect it mid-build.
- ✓PriorityQueue offer/poll are both O(log n) backed by a binary heap array, so the n-1 merges give the standard O(n log n).
What Huffman Encoding actually is
Huffman Encoding in Java: what you actually reach for
Java implementation
import java.util.*;
sealed interface HuffNode permits Leaf, Internal {
int weight();
}
record Leaf(int weight, char symbol) implements HuffNode {}
record Internal(int weight, HuffNode left, HuffNode right) implements HuffNode {}
class Huffman {
static HuffNode buildTree(String text) {
Map<Character, Integer> freqs = new HashMap<>();
for (char c : text.toCharArray()) freqs.merge(c, 1, Integer::sum);
PriorityQueue<HuffNode> pq = new PriorityQueue<>(Comparator.comparingInt(HuffNode::weight));
for (var e : freqs.entrySet()) pq.offer(new Leaf(e.getValue(), e.getKey()));
while (pq.size() > 1) {
HuffNode a = pq.poll();
HuffNode b = pq.poll();
pq.offer(new Internal(a.weight() + b.weight(), a, b));
}
return pq.poll();
}
static void buildCodes(HuffNode node, String prefix, Map<Character, String> table) {
switch (node) { // exhaustive: sealed interface
case Leaf l -> table.put(l.symbol(), prefix.isEmpty() ? "0" : prefix);
case Internal i -> {
buildCodes(i.left(), prefix + "0", table);
buildCodes(i.right(), prefix + "1", table);
}
}
}
}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(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Huffman Encoding?
java.util.PriorityQueue<E> is a genuine binary min-heap out of the box, unlike Go, no adapter is needed, only a Comparator (or a natural Comparable ordering on the element type) to define priority. Map<Character, Integer> (or a primitive-friendly alternative like an int[256] array for byte-level Huffman) builds the frequency table. sealed interfaces (Java 17+) express the leaf/internal split as a closed hierarchy; exhaustively switching over that hierarchy with pattern-matching switch (case Leaf l -> ..., no default arm needed) requires Java 21+, since that switch form stayed a preview feature through JDK 17-20 and was only finalized in JDK 21 (JEP 441).
What is the most common Java mistake when implementing Huffman Encoding?
PriorityQueue's iteration order is NOT sorted order, only poll() and peek() respect priority; iterating the queue directly (for-each, or passing it to a stream) yields elements in the internal heap-array order, which looks almost-sorted for small inputs and misleads people into believing they can inspect it mid-build. The classic correctness bug here is forgetting to give the comparator a tie-breaker: PriorityQueue is not required to be a stable sort on ties, so two runs over data with equal-weight symbols can legally produce two different (both still optimal, but different) trees, which breaks any test asserting an exact expected bitstring rather than just decodability.
How does Huffman Encoding actually perform in Java?
PriorityQueue offer/poll are both O(log n) backed by a binary heap array, so the n-1 merges give the standard O(n log n). Records (Leaf, Internal) are heap-allocated immutable objects like any Java object; for a bounded 256-symbol alphabet this is well under microsecond territory, and the JIT will typically inline the small accessor methods (weight(), left(), right()) after warmup. Time complexity is O(n log n) and space is O(n).
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 Devin, 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.