Trie Prefix Search And Autocomplete (Java)
Build a Java trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.
Code
import java.util.*;
public class Trie {
static class Node { Map<Character, Node> children = new HashMap<>(); boolean isWord; int freq; }
Node root = new Node();
public void insert(String word, int freq) {
Node node = root;
for (char ch : word.toCharArray()) { node = node.children.computeIfAbsent(ch, k -> new Node()); }
node.isWord = true; node.freq += freq;
}
public List<String> suggest(String prefix, int limit) {
Node node = root;
for (char ch : prefix.toCharArray()) { node = node.children.get(ch); if (node == null) return List.of(); }
List<String[]> results = new ArrayList<>();
dfs(node, prefix, results);
results.sort((a, b) -> Integer.compare(Integer.parseInt(b[1]), Integer.parseInt(a[1])));
return results.stream().limit(limit).map(r -> r[0]).toList();
}
void dfs(Node n, String path, List<String[]> out) { if (n.isWord) out.add(new String[]{path, String.valueOf(n.freq)}); for (var e : n.children.entrySet()) dfs(e.getValue(), path + e.getKey(), out); }
}How it works
All of the logic lives in the classes Trie and Node and the functions insert and suggest.
Repetition is confined to for (char ch : word.toCharArray()) { node = node.children.computeIfAbsent(ch, k -> new Node()); } — the rest of the file is straight-line. The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Putting it to use
The primary signature is public void insert(String word, int freq)
Core lines
return results.stream().limit(limit).map(r -> r[0]).toList();
for (char ch : prefix.toCharArray()) { node = node.children.get(ch); if (node == null) return List.of(); }
results.sort((a, b) -> Integer.compare(Integer.parseInt(b[1]), Integer.parseInt(a[1])));
Interactive Tools for This Topic
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `insert`, `suggest` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.