The Wayback Machine - https://web.archive.org/web/20240811033212/https://www.geeksforgeeks.org/java-program-to-implement-hash-trie/
Open In App

Java Program to Implement Hash Trie

Last Updated : 02 Feb, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Program to Implement Hash Table Chaining with List Heads
A hash table is a data structure that executes a connected array, it is a structure that maps keys to its values. It uses a hash function to calculate an index position for the keys, also called hash code. It will store key and value pair in an array of buckets, and from that bucket, the values can be easily found with the help of keys. To find the
4 min read
Java Program to Implement Hash Tables with Double Hashing
Double hashing is a technique in an open addressing scheme. and there is the ordinary hash function. In an open addressing scheme, the actual hash function is taking the ordinary hash function when its space is not empty then it will perform another hash function to get some space to insert. Double hashing is a collision resolving technique in an O
10 min read
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
Hash Tables(similar to tables in general) provide a subset of the dynamic set operations. Usually, a set of keys are mapped with some values based on certain relations. However, there might be situations when different keys map to the same position provided by the Hash function, which leads to a collision. One of the ways to overcome this situation
5 min read
How to Implement a Custom Hash function for Keys in a HashMap in Java?
In Java, HashMap is the data structure that implements the Map interface. This is used to save the data in the form of key-value pairs. In this article, we will learn how to implement a Custom Hash function for keys in a HashMap in Java. In Java, implementing the custom hash function for keys in a HashMap requires overriding the hashcode() method i
2 min read
Implementing Patricia Trie in Java
A Patricia Trie or prefix Tree or radix Tree is an ordered structured tree, which takes the applications of usually the data it stores. A node's position in the tree defines the key with which that node is associated, which makes tries different in comparison to binary search Trees, in which a node stores a key that corresponds only to that node. E
13 min read
Longest prefix matching - A Trie based solution in Java
Given a dictionary of words and an input string, find the longest prefix of the string which is also a word in dictionary. Examples: Let the dictionary contains the following words: {are, area, base, cat, cater, children, basement} Below are some input/output examples: -------------------------------------- Input String Output ---------------------
4 min read
Trie Data Structure in Java
A Trie Data Structure is nothing but it is a tree-like data structure which is used to efficiently store and retrieve the dynamic set of Strings or Keys. It is certainly used for tasks that will involve searching for strings with common prefix like auto-complete or spell-checking applications. In this article, we will learn about Trie Data Structur
4 min read
Java Program to Implement Control Table in Java
Control tables will be tables that control the control stream or have a significant influence on program control. There are no unbending guidelines about the structure or substance of a control table—its passing trait is its capacity to coordinate the control stream somehow or another through "execution" by a processor or mediator. The plan of such
3 min read
MD5 hash in Java
To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security. MessageDigest Class provides following cryptographic hash function to find hash value of a text, they are: MD5 SHA-1 SHA-256 This Algorithms are initialize in static method called getInstance(). After selecting the algorithm it calculate
2 min read
SHA-384 Hash In Java
The SHA-2 family of cryptographic hash functions consists of six hash functions. These are: SHA-224, with 224 bit hash values SHA-256, with 256 bit hash values SHA-384, with 384 bit hash values SHA-512, with 512 bit hash values SHA-512/224, with 512 bit hash values SHA-512/256, with 512 bit hash values Among these, SHA-256 and SHA-512 are the most
3 min read
three90RightbarBannerImg