Partial search in HashMap

前端 未结 5 765
后悔当初
后悔当初 2020-11-29 03:55

I need to create phone book kind of thing. It contains name & number. Now when I type letters matching list should be returned. For the example given below, when I type

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 04:40

    Yeah, a HashMap is not the right data structure for this. As Bozho said, a Trie would be the right one.

    With Java's on-board tools, a TreeMap (or any SortedMap, actually) could be used:

    public  SortedMap filterPrefix(SortedMap baseMap, String prefix) {
        if(prefix.length() > 0) {
            char nextLetter = prefix.charAt(prefix.length() -1) + 1;
            String end = prefix.substring(0, prefix.length()-1) + nextLetter;
            return baseMap.subMap(prefix, end);
        }
        return baseMap;
    }
    

    The output would even be sorted by key.

    Here an usage example:

    SortedMap nameNum = new TreeMap();
    // put your phone numbers
    
    String prefix = ...;
    for(Map.Entry entry : filterPrefix(nameNum, prefix).entrySet()) {
        System.out.println(entry);
    }
    

    If you want your prefix filter to not be depending on case differences, use a suitable Comparator for your map (like a Collator with a suitable strength setting, or String.CASE_INSENSITIVE_ORDER).

提交回复
热议问题