开发者

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

开发者 https://www.devze.com 2023-01-25 06:29 出处:网络
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 dis开发者_如何学运维play

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 dis开发者_如何学运维play starting with AB company name. I am storing company name in hash map


  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.


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.


You can loop over the keyset and check each key. For example:

final String searchPrefix = "AB";
for(String key : map.keySet()){
    if(key.startsWith(searchPrefix)){
        System.out.println(map.get(key));
    }
}

Or, you can loop over the entries in the map.

final String searchPrefix = "AB";
for(Entry<String,String> e : map.entrySet()){
    if(e.getKey().startsWith(searchPrefix)){
        System.out.println(e.getValue());
    }
}


you should look into regex (regular expressions)

http://download.oracle.com/javase/tutorial/essential/regex/

your company names are Strings then you can use

String regex = "A*";
myString.matches(regex);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号