Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search like LIKe operator in sql in hash map in java

Tags:

java

I want to search a hash map depending on the user input. Suppose a user give value 'A',I have to display starting with A company name and if user give value 'AB' I have to display starting with AB company name. I am storing company name in hash map

like image 832
mohan Avatar asked Dec 05 '22 00:12

mohan


2 Answers

  1. Use a NavigableSet.

    Example:

    NavigableSet<String> company=new TreeSet<String>(); 
    Set<String> filteredSet=company.tailSet(prefix);
    for(String str:filteredSet) {
     if(str.startsWith(prefix))
      //add to list
     else
      break;
    }
    
  2. Use a radix tree [wiki] or trie [wiki] if you are concerned about performance.The radix tree is more memory efficient compared to a trie.

like image 60
Emil Avatar answered Dec 07 '22 15:12

Emil


Hash maps are only really good at finding exact matches based on some idea of equality which can be appropriately hashed.

Two options:

  • Just go with a list instead, and search it linearly. For relatively small amounts of data, this is likely to work absolutely fine.
  • Find or implement a trie (or prefix tree) which will basically start at a root node and descend for each character the user has typed - the results are all "valid endpoint" nodes below the node reached at the end of descending the user input.
like image 24
Jon Skeet Avatar answered Dec 07 '22 15:12

Jon Skeet