HashMap 中的部分搜索 [英] Partial search in HashMap

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

问题描述

我需要创建电话簿之类的东西.它包含名称 &数字.现在当我输入字母匹配列表时应该返回.对于下面给出的示例,当我输入 H 时,应该返回一个包含 Harmer、Harris、Hawken、Hosler 的列表.当输入 Ha then list 只包含 Harmer、Harris、Hawken 时,应该返回.

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;
}

输出甚至可以按关键字排序.

The output would even be sorted by key.

这是一个用法示例:

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天全站免登陆