how to search like LIKe operator in sql in hash ma

2020-02-11 06:36发布

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

标签: java
4条回答
够拽才男人
2楼-- · 2020-02-11 06:55

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.
查看更多
祖国的老花朵
3楼-- · 2020-02-11 07:04

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);
查看更多
Ridiculous、
4楼-- · 2020-02-11 07:15
  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.

查看更多
在下西门庆
5楼-- · 2020-02-11 07:21

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());
    }
}
查看更多
登录 后发表回答