Java program to find all close matches of input string from a list

JavaObject Oriented ProgrammingProgramming

To find all close matches of input string from a list, the Java code is as follows −


 Live Demo

import java.util.*;
public class Demo{
   static String string_encoding(String str){
      HashMap<Character, Integer> my_map = new HashMap<>();
      String result = "";
      int i = 0;
      char ch;
      for (int j = 0; j < str.length(); j++) {
         ch = str.charAt(j);
         if (!my_map.containsKey(ch))
         my_map.put(ch, i++);
         result += my_map.get(ch);
      return result;
   static void match_words( String[] my_arr, String my_pattern){
      int len = my_pattern.length();
      String hash_val = string_encoding(my_pattern);
      for (String word : my_arr){
         if (word.length() == len && string_encoding(word).equals(hash_val))
         System.out.print(word + " ");
   public static void main(String args[]){
      String[] my_arr = { "mno", "aabb", "pqr", "xxyy", "mmnn" };
      String my_pattern = "ddcc";
      System.out.println("The patterns similar to ddcc in the array are :");
      match_words(my_arr, my_pattern);


The patterns similar to ddcc in the array are :
aabb xxyy mmnn

A class named Demo contains a function called ‘string_encoding’. This function creates a hashmap and iterates over the string to check if there are any patterns that match the string in question.

Another function named 'match_words' is defined that calls the 'string_encoding' function and checks to see if there is any match in the arrays with the pattern of the string that is given as a reference. If found, the word is returned. In the main function, the string array is defined along with a pattern. The 'match_words' function is called on this pattern. The relevant output is displayed on the console.

Updated on 07-Jul-2020 09:46:46