39 lines
1.0 KiB
Java
39 lines
1.0 KiB
Java
package io.gitlab.jfronny.libjf.web.impl.variant.shared;
|
|
|
|
import it.unimi.dsi.fastutil.chars.Char2ObjectArrayMap;
|
|
import it.unimi.dsi.fastutil.chars.Char2ObjectMap;
|
|
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.function.Function;
|
|
import java.util.stream.Collectors;
|
|
|
|
public class Trie<T> {
|
|
public final Char2ObjectMap<Trie<T>> next;
|
|
public T content;
|
|
|
|
public Trie() {
|
|
this.next = new Char2ObjectArrayMap<>();
|
|
}
|
|
|
|
public void add(Map<String, T> next) {
|
|
next.forEach(this::add);
|
|
}
|
|
|
|
public void add(String key, T value) {
|
|
if (key.isEmpty()) this.content = value;
|
|
else this.next.computeIfAbsent(key.charAt(0), k -> new Trie<>())
|
|
.add(key.substring(1), value);
|
|
}
|
|
|
|
public static <T> Trie<T> of(Map<String, T> source) {
|
|
Trie<T> root = new Trie<>();
|
|
root.add(source);
|
|
return root;
|
|
}
|
|
|
|
public static Trie<String> of(List<String> source) {
|
|
return of(source.stream().collect(Collectors.toMap(Function.identity(), Function.identity())));
|
|
}
|
|
}
|