在HashMap中进行部分搜索 [英] Partial search in HashMap

查看:153
本文介绍了在HashMap中进行部分搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建电话簿的东西。它包含名称&数。现在当我输入字母匹配列表应该被返回。对于下面给出的示例,当我输入H时,应该返回包含Harmer,Harris,Hawken,Hosler的列表。当哈哈然后列表只包含哈默尔,哈里斯,霍肯应该归还。

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 H, a list containing Harmer, Harris, Hawken, Hosler should be returned. When type Ha then list containing only Harmer, Harris, Hawken should be returned.

  Map<String, String> nameNum = new HashMap<String, String>();

  nameNum.put("Brown", "+1236389023");
  nameNum.put("Bob", "+1236389023");
  nameNum.put("Harmer", "+1236389023");
  nameNum.put("Harris", "+1236389023");
  nameNum.put("Hawken", "+1236389023");
  nameNum.put("Hosler", "+1236389023");

任何想法如何实现?
提前感谢。

Any idea how achieve it? Thanks in advance.

推荐答案

是的,HashMap不是正确的数据结构。正如Bozho所说, Trie 将是正确的。

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

使用Java的板载工具,TreeMap(或任何 SortedMap ,实际上)可以使用:

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

public <V> SortedMap<String, V> filterPrefix(SortedMap<String,V> 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;
}

输出甚至会按键排序。

这里有一个用法示例:

SortedMap<String, String> nameNum = new TreeMap<String, String>();
// put your phone numbers

String prefix = ...;
for(Map.Entry<String,String> entry : filterPrefix(nameNum, prefix).entrySet()) {
    System.out.println(entry);
}

如果您希望前缀过滤器不取决于案例差异,请使用适合您的地图的比较器(如 Collat​​or ,具有合适的强度设置,或 String.CASE_INSENSITIVE_ORDER

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).

这篇关于在HashMap中进行部分搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆