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); }
}Report a problem with this exampleOpens a pre-filled issue on GitHub.