我有一个 java 属性文件,其中包含国家/地区名称和代码的键/值对。我会将此文件的内容加载到 List 或 HashMap 等 Collection 中。
然后,我希望用户能够搜索一个国家/地区,例如,如果他们在文本框中输入“Aus
”并单击“提交”,那么我想搜索我拥有的集合,其中包含国家/地区代码/名称的键/值对(例如 AUS=>澳大利亚),并返回匹配的国家/地区。
除了循环遍历集合元素并使用 charAt()
之外,还有其他更有效的方法吗?
最佳答案
如果性能很重要,您可以使用 TreeSet 或 TreeMap 来保存国家/地区名称,并执行以下操作可用于识别以给定字符串开头的国家/地区。
NavigableMap<String, String> countries = new TreeMap<String, String>();
countries.put("australia", "Australia");
...
String userText = ...
String tmp = userText.toLower();
List<String> hits = new ArrayList<String>();
Map.Entry<String, String> entry = countries.ceilingEntry(tmp);
while (entry != null && entry.getKey().startsWith(tmp)) {
hits.add(entry.getValue());
entry = map.higherEntry(entry.getKey());
}
// hits now contains all country names starting with the value of `userText`,
// ignoring differences in letter case.
这是O(logN)
,其中N 是国家/地区的数量。相比之下,集合的线性搜索是O(N)
关于java - 在 Java 中搜索集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1318603/