java
28 lines · 7 steps
Ranking the most frequent words in Java
A stream pipeline tokenizes text, counts each word, and returns the top entries in a stable, ordered map.
Explained by
highlit
1import java.util.Comparator;
2import java.util.LinkedHashMap;
3import java.util.Map;
4import java.util.regex.Pattern;
5import java.util.stream.Collectors;
6
7public final class WordFrequencyAnalyzer {
8
9 private static final Pattern WORD = Pattern.compile("[\\p{L}']+");
10
11 public Map<String, Long> topWords(String text, int limit) {
12 return WORD.matcher(text.toLowerCase())
13 .results()
14 .map(match -> match.group())
15 .collect(Collectors.groupingBy(word -> word, Collectors.counting()))
16 .entrySet()
17 .stream()
18 .sorted(Map.Entry.<String, Long>comparingByValue()
19 .reversed()
20 .thenComparing(Map.Entry.comparingByKey()))
21 .limit(limit)
22 .collect(Collectors.toMap(
23 Map.Entry::getKey,
24 Map.Entry::getValue,
25 (a, b) -> a,
26 LinkedHashMap::new));
27 }
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Compiling a regex once as a static field avoids recompiling the pattern on every call.
- 2Collectors.groupingBy paired with Collectors.counting turns a stream of items into a frequency map in one pass.
- 3LinkedHashMap as the toMap supplier preserves the sorted iteration order that a plain HashMap would discard.
Related explainers
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/ranking-the-most-frequent-words-in-java-explained-java-3f0f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.