Scrivio Interview library
CodingIntermediate8 min read · updated 12 November 2026

Write Java code that reads a 2 GB text log file and prints the 10 most frequent words, case-insensitive, without loading the file into memory. Discuss complexity and whether a parallel stream helps.

We stream the file line by line with try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)), split each line into words with a precompiled Pattern and splitAsStream, lowercase each word with Locale.ROOT, and count into a HashMap with merge(word, 1L, Long::sum), or with groupingBy and counting(). Memory is bounded by the number of unique words, not the 2 GB file size. For the top 10, a min-heap PriorityQueue of size 10 costs O(u log 10) over u unique words, against O(u log u) for sorting all entries. A parallel stream helps only if splitting and counting, not disk reading, is the bottleneck: Files.lines can split UTF-8 files for parallel work since JDK 9, but we must measure and then use a concurrent collector.

Background to this question

Counting words in a large file is a small version of a very common production job: finding the most frequent error codes in logs, the busiest customers in an access log, or the hottest search terms. The 2 GB size rules out reading everything into a list, so the question checks that we know how to stream data, how memory really grows, how to pick the top k efficiently, and whether parallelism helps an I/O-heavy job. In this answer, we will recap why streaming keeps memory small, write the counting pipeline, choose the top 10 two ways, work out the complexity and memory, and then decide about parallel streams with measurements.

1A Quick Recap: Streaming Instead of Loading

Files.readAllLines would load all 2 GB into memory as String objects, and with String objects at one byte per character for Latin-1 text and two bytes otherwise, plus some 40 bytes of overhead per line, that can need several gigabytes of heap. Files.lines(path, charset) instead returns a lazy Stream<String>: it reads a buffer of the file at a time and hands out one line at a time, so only the current chunk is in memory.

The stream holds an open file handle, so we must close it. Files.lines is one of the few streams that needs closing, and try-with-resources does it even when an exception is thrown halfway.

2Counting the Words

We split lines on runs of non-word characters, normalize case, and count.

Java
static final Pattern NON_WORD = Pattern.compile("[^\\p{L}\\p{N}']+"); // compiled once
static Map<String, Long> countWords(Path path) throws IOException {
Map<String, Long> counts = new HashMap<>();
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
lines.flatMap(NON_WORD::splitAsStream)
.filter(w -> !w.isEmpty()) // a leading separator gives ""
.map(w -> w.toLowerCase(Locale.ROOT))
.forEach(w -> counts.merge(w, 1L, Long::sum));
}
return counts;
}
// "The cat saw the other cat." -> {the=2, cat=2, saw=1, other=1}

A common first attempt is Pattern.compile("\\W+"). That works for English, but in Java \W means anything that is not [a-zA-Z_0-9] unless we enable the UNICODE_CHARACTER_CLASS flag, so a word such as cafe written with an accented final e (U+00E9) would lose that letter and be counted as caf. The class [^\p{L}\p{N}']+ splits on anything that is not a Unicode letter, digit or apostrophe, which keeps accented words and contractions together. Whatever we choose, we compile the pattern once; calling String.split with a regex for each of millions of lines would recompile it each time unless it is a single character.

merge(w, 1L, Long::sum) inserts 1 for a new word and adds 1 to an existing count, in one map lookup. The equivalent collector is groupingBy(w -> w, counting()), which is more declarative; the merge version has slightly less overhead and is easy to reason about in a sequential stream. One caution: a malformed byte sequence in the file makes Files.lines throw UncheckedIOException wrapping a MalformedInputException, so for logs of mixed origin we may read with a decoder set to replace bad input instead.

3Choosing the Top 10

With the counts in hand, we need the 10 largest. Sorting all entries is simple; a small heap is cheaper when there are many unique words.

Java
// Simple: sort every entry, O(u log u)
List<Map.Entry<String, Long>> top = counts.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(10)
.toList();
// Cheaper: keep only 10 entries in a min-heap, O(u log 10)
PriorityQueue<Map.Entry<String, Long>> heap =
new PriorityQueue<>(Map.Entry.comparingByValue()); // smallest count on top
for (Map.Entry<String, Long> e : counts.entrySet()) {
heap.offer(e);
if (heap.size() > 10) heap.poll(); // drop the smallest
}
List<Map.Entry<String, Long>> top10 = new ArrayList<>(heap);
top10.sort(Map.Entry.<String, Long>comparingByValue().reversed()); // largest first
Step throughFrom 2 GB file to top 10
  1. Files.lines(path, UTF_8)lazy, one buffer at a time, closed by try
  2. flatMap: split each line into wordsprecompiled pattern, skip empty strings
  3. lowercase with Locale.ROOTcase-insensitive counting
  4. counts.merge(word, 1L, Long::sum)memory grows with unique words only
  5. min-heap of size 10 over the entriesO(u log 10)
  6. sort the 10 entries, largest firstprint them

6 steps in order. Play them, or step through them one at a time.

The heap version works because a min-heap keeps its smallest element at the top. Whenever it grows past 10 entries we remove the smallest, so after all entries it holds the 10 largest. Each offer and poll costs O(log 10), effectively constant. For 2 million unique words, sorting does about 2 million x 21 comparisons, while the heap does about 2 million x 4. Both are fast at this size, but the heap uses only 10 slots instead of a sorted copy of all entries. Ties between equal counts come out in arbitrary order unless we add thenComparing on the key.

4Complexity and Memory

Reading and splitting touches every character once, so the main cost is O(N) for N characters, about 2 billion here. Counting is one hash map operation per word, O(W) on average for W words. Choosing the top 10 is O(u log 10) for u unique words. So the whole job is linear in the file size.

Memory is bounded by the number of unique words, not by the file size, because each line is discarded after it is split. Natural language and log text usually have far fewer unique words than total words: a 2 GB file might hold 300 million words but only a few hundred thousand to a few million distinct ones. Each map entry costs roughly 100 bytes including the String, the Long and the node, so even 2 million unique words is around 200 MB, which fits in an ordinary heap. If the vocabulary could be unbounded, such as unique ids in a log, we would need an approximate structure like a Count-Min Sketch with a small heap instead.

5Does a Parallel Stream Help?

Two conditions decide. First, the stream must be able to split its work. Since JDK 9, Files.lines on a regular file with UTF-8, US-ASCII or ISO-8859-1 can split the file into byte ranges for parallel processing; with other charsets it reads sequentially and parallel() gains little. Second, the job must be CPU-bound. Reading 2 GB from a fast SSD takes a few seconds, and from a network disk much longer. If the disk is the bottleneck, more threads only wait on it together.

If measurements show that splitting and counting dominate, which happens with a fast disk or a file already in the operating system's page cache, parallelism can help. But the forEach with HashMap.merge above would then be a data race, because HashMap is not thread-safe. The parallel version uses a concurrent collector: lines.parallel().flatMap(...).collect(Collectors.groupingByConcurrent(w -> w, Collectors.counting())), which puts everything into one ConcurrentHashMap without a costly merge of per-thread maps. Parallel streams also run on the common ForkJoinPool shared with the rest of the JVM, so in a server I would rather run this as a batch job than inside a request. And I would measure both versions with the real file before deciding.

6Follow-up questions

How would you do it for 200 GB across many machines?

I would use the map-reduce pattern, either by hand or with a framework like Spark. Each machine reads a slice of the data and counts words locally. Taking each machine's local top 10 and merging them would be wrong, because a word that is 11th everywhere can be first overall. Instead, each machine sends its counts partitioned by a hash of the word, so every word's counts arrive at exactly one reducer, which sums them and computes its own top 10. Because each word lives on one reducer, merging the reducers' top 10 lists gives the correct global top 10. If an approximate answer is acceptable, sketches such as Count-Min with a heap use far less network and memory.

Why use a min-heap and not a max-heap for the top 10?

Because we want to throw away small counts as we go. In a min-heap of size 10, the top is the smallest of the current 10 best, so comparing a new entry against it and dropping the smaller costs O(log 10). A max-heap of all u entries would also work, polling 10 times at the end, but it holds every entry and costs O(u) memory and O(u) to build.

7Conclusion

In this answer, we counted words in a 2 GB file without loading it: Files.lines in try-with-resources reads lazily, a precompiled Unicode-aware pattern splits lines, toLowerCase(Locale.ROOT) normalizes case, and HashMap.merge counts with memory bounded by unique words. A min-heap of size 10 picks the top 10 in O(u log 10), against O(u log u) for sorting all entries. Parallel streams help only when the work is CPU-bound and the file can be split, which Files.lines supports for UTF-8 since JDK 9, and then only with a concurrent collector such as groupingByConcurrent, after measuring.

What to say in the interviewAbout 100 seconds aloud

Open with

I would stream the file rather than load it. In a try-with-resources I open Files.lines with UTF-8, so the file handle is closed even on errors, and I flatMap each line into words with a precompiled pattern and splitAsStream, skipping the empty strings a leading separator produces.

Then, if they want more

I lowercase each word with Locale.ROOT, so the result does not depend on the server's locale, and count into a HashMap with merge, word, 1L, Long::sum. groupingBy with counting would work too.

The important property is that memory grows with the number of unique words, maybe a few hundred thousand or a couple of million, not with the 2 GB file.

For the top 10, I would keep a min-heap of size 10 ordered by count, and drop the smallest whenever it grows past 10, which is O(u log 10), instead of sorting all u entries, which is O(u log u). Overall the job is linear in the file size. On parallel streams, I would measure first.

Since JDK 9 Files.lines can split UTF-8 files, but the job is often limited by disk reading, and then threads just wait together. If it does turn out CPU-bound, I cannot keep the HashMap merge, because that would be a data race, so I would use groupingByConcurrent with counting.

I would also note that the backslash W pattern only treats ASCII letters as word characters, so for international text I would split on Unicode letter and digit classes.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write Java code that reads a 2 GB text log file and prints the 10 most frequent words...": https://scrivio-interview-library.netlify.app/java/coding-problems/5065029da0/