Java Program to Implement Hash Trie
Last Updated :
02 Feb, 2021
A trie isn't something CS students might have spent that much time on in college but it's really very important for interviews. A trie is a data structure that is actually a type of tree, but it's often used to store an associative array or a dynamic set where the keys are usually characters or strings, and its position in the tree defines the key with which it is associated. The way that it works is that every successor of a node have a common prefix of the string associated with that node which means each node might store a, just a character as its data but then if we look at the path from the root down to that node, that note is really representing a word or a part of a word, and so what allows us to do is, very quick lookups of a particular kind of word or character.

Java Code:
- Importing required module:
Java
import java.io.*;
import java.util.*;
- Now, we will make a class TrieHash in which we will implement a HashMap, it will also contain two constructors with zero and single array argument, a function to add characters to hash trie and a function to search for the specific string in the hash trie.
Java
class TrieHash {
// implementing a HashMap
private HashMap<Character, HashMap> origin;
// implementing a zero-argument constructor
public TrieHash()
{
// creating a new HashMap
origin = new HashMap<Character, HashMap>();
}
// implementing another constructor
// with an array as a parameter
public TrieHash(String[] array)
{
origin = new HashMap<Character, HashMap>();
// attaching that array string in the trie
for (String c : array)
attach(c);
}
// attach function to add character to the trie
public void attach(String str)
{
HashMap<Character, HashMap> node = origin;
int i = 0;
while (i < str.length()) {
// if node already contains that key,
// we will simply point that node
if (node.containsKey(str.charAt(i))) {
node = node.get(str.charAt(i));
}
else {
// else we will make a new hashmap with
// that character and then point it.
node.put(str.charAt(i),
new HashMap<Character, HashMap>());
node = node.get(str.charAt(i));
}
i++;
}
// putting 0 to end the string
node.put('\0', new HashMap<Character, HashMap>(0));
}
// function to search for the specific
// string in the hash trie
public boolean search(String str)
{
HashMap<Character, HashMap> presentNode = origin;
int i = 0;
while (i < str.length()) {
// will search for that character if it exists
if (presentNode.containsKey(str.charAt(i))) {
presentNode
= presentNode.get(str.charAt(i));
}
else {
// if the character does not exist
// that simply means the whole string
// will also not exists, so we will
// return false if we find a character
// which is not found in the hash trie
return false;
}
i++;
}
// this will check for the end string,
// and if the whole string is found,
// it will return true else false
if (presentNode.containsKey('\0')) {
return true;
}
else {
return false;
}
}
}
Â
Now all the required functions are coded, now we will test those functions with the user input. For this, we will again make a new class to test our hash trie which will prompt the user to enter the words for trie and the word to be searched for.
Java
public class Main {
// unreported exception IOException must be caught or
// declared to be thrown
public static void main(String[] args)
throws IOException
{
BufferedReader br
= new BufferedReader(new InputStreamReader(
System.in)); // this will accepts the words
// for the hash trie
System.out.println(
"Enter the words separated with space to be entered into trie");
// will read the line which user will
// provide with space separated words
String input = br.readLine();
// it will split all the words
// and store them in the string array
String[] c = input.split(" ");
// now we will use constructor with string array as
// parameter and we will pass the user entered
// string in that constructor to construct the hash
// trie
TrieHash trie = new TrieHash(c);
System.out.println(
"\nEnter the word one by one to be searched in hash-trie");
String word = br.readLine();
// this will search for the word in out trie
if (trie.search(word)) {
System.out.println("Word Found in the trie");
}
else {
System.out.println(
"Word NOT Found in the trie!");
}
}
}
Â
Below is the implementation of the problem statement:
Java
import java.io.*;
import java.util.*;
class TrieHash {
// implementing a HashMap
private HashMap<Character, HashMap> origin;
// implementing a zero-argument constructor
public TrieHash()
{
// creating a new HashMap
origin = new HashMap<Character, HashMap>();
}
// implementing another constructor
// with an array as a parameter
public TrieHash(String[] array)
{
origin = new HashMap<Character, HashMap>();
// attaching that array string in the trie
for (String c : array)
attach(c);
}
// attach function to add
// character to the trie
public void attach(String str)
{
HashMap<Character, HashMap> node = origin;
int i = 0;
while (i < str.length()) {
// if node already contains thatkey,
// we will simply point that node
if (node.containsKey(str.charAt(i))) {
node = node.get(str.charAt(i));
}
else {
// else we will make a new hashmap with
// that character and then point it.
node.put(str.charAt(i),
new HashMap<Character, HashMap>());
node = node.get(str.charAt(i));
}
i++;
}
// putting 0 to end the string
node.put('\0', new HashMap<Character, HashMap>(0));
}
// function to search for the
// specific string in the hash trie
public boolean search(String str)
{
HashMap<Character, HashMap> presentNode = origin;
int i = 0;
while (i < str.length()) {
// will search for that character
// if it exists
if (presentNode.containsKey(str.charAt(i))) {
presentNode
= presentNode.get(str.charAt(i));
}
else {
// if the character does notexist that
// simply means the whole string will
// also not exists, so we will return
// false if we find a character which
// is not found in the hash trie
return false;
}
i++;
}
// this will check for the end string,
// and if the whole string is found,
// it will return true else false
if (presentNode.containsKey('\0')) {
return true;
}
else {
return false;
}
}
}
public class Main {
// unreported exception IOException
// must be caught or declared to be thrown
public static void main(String[] args)
throws IOException
{
// this will accepts the words for the hash trie
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println(
"Enter the words separated with space to be entered into trie");
// will read the line which user will
// provide with space separated words
String input = br.readLine();
// it will split all the words and
// store them in the string array
String[] c = input.split(" ");
// now we will use constructor with string
// array as parameter and we will pass the
// user entered string in that constructor
// to construct the hash trie
TrieHash trie = new TrieHash(c);
System.out.println(
"How many words you have to search in the trie");
String count = br.readLine();
int counts = Integer.parseInt(count);
for (int i = 0; i < counts; i++) {
System.out.println(
"\nEnter the word one by one to be searched in hash-trie ");
String word = br.readLine();
// this will search for the word in out trie
if (trie.search(word)) {
System.out.println(
"Word Found in the trie");
}
else {
System.out.println(
"Word NOT Found in the trie!");
}
}
}
}
Output1:
Output2:
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read