我有一个arraylist<string>
的话。我使用它排序Collections.sort(wordsList);
我将此数组用于自动建议下拉框,以便当用户输入字母时,他们会收到与他们输入的内容类似的建议列表。
我如何在这个数组中搜索字符串前缀,假设用户输入“mount”并且数组包含单词“mountain”,我如何搜索这个数组并返回类似的值。
到目前为止,这是我的代码:
public List<Interface> returnSuggestedList(String prefix) {
String tempPrefix = prefix;
suggestedPhrases.clear();
//suggestedPhrases = new ArrayList<Interface>();
//Vector<String> list = new Vector<String>();
//List<Interface> interfaceList = new ArrayList<Interface>();
Collections.sort(wordsList);
System.out.println("Sorted Vector contains : " + wordsList);
int i = 0;
while (i != wordsList.size()) {
int index = Collections.binarySearch(wordsList, prefix);
String tempArrayString = wordsList.get(index).toString();
if (tempArrayString.toLowerCase().startsWith(prefix.toLowerCase())) {
ItemInterface itemInt = new Item(tempArrayString);
suggestedPhrases.add(itemInt);
System.out.println(suggestedPhrases.get(i).toString());
System.out.println("Element found at : " + index);
}
i++;
}
return suggestedPhrases;
}
最基本的方法是
List<String> result = new ArrayList<String>();
for(String str: words){
if(str.contains(keyword){
result.add(str);
}
}
如果您只关心的话,您可以改进此版本startWith
代替contains
然后你可以在 HashMap 中分配单词,你将缩小搜索范围
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)