根据字符串搜索 Java 集合
我有一个具有以下结构的集合...
ArrayList<String[]> schools = new ArrayList<String[]>();
我还有一个字符串“United Berkley”
现在我想搜索“schools”上面提到的字符串并返回String[] 如果任何 String[] 数组中有任何匹配项。
我有基本的代码,但找不到所需的正则表达式。
String target = this.Schools.get(s)[a];
if (target.matches("*")) {
schools.add(this.Schools.get(s));
}
I have a collection which has following structure...
ArrayList<String[]> schools = new ArrayList<String[]>();
I also have a string say "United Berkley"
Now I want to search "schools" for the above mentioned string and return String[] if there is any match in any the String[] array.
I have that basic code but lost to find desired regex for it.
String target = this.Schools.get(s)[a];
if (target.matches("*")) {
schools.add(this.Schools.get(s));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的学校数据结构看起来有点……奇怪。
您确定您想要的不是
ArrayList
吗?如果是这种情况,那么您可以使用:
Your
schools
data structure looks a bit... weird.Are you sure what you wanted is not
ArrayList<String>
?If that's the case, then you can just use:
这个怎么样?
打印“找到目标”。
How about this?
prints "Found target".
只需使用 String.equals(your-String) 并循环遍历数组即可匹配学校。或者使用 list.contains(your-String)
但我想使用 HashMap 将为此类事物提供更好的访问时间。
Just use String.equals(your-String) and loop through the array to match the schools. Or use list.contains(your-String)
But I guess using a HashMap will provice better access times for that kind of things.
您不需要正则表达式来搜索已知字符串 - 只需使用
target.equals ("United Berkley")
。您可以通过确保您的 String[] 数组已排序来使自己更轻松 - 使用 Arrays.sort (...) 来保持它们的顺序,并使用 Arrays.binarySearch (...) 来快速搜索它们。不过,我确实质疑您的数据结构的布局 - 这似乎不是做您想做的事情的最自然的方式。一个
HashMap
甚至一个简单的排序List
会更好。You don't need a regular expression to search for a known string - just use
target.equals ("United Berkley")
. You can make it easier on yourself by making sure that your String[] arrays are sorted - use Arrays.sort (...) to keep them in order and the use Arrays.binarySearch (...) to search them quickly.I do question the layout of your data structures though - it doesn't seem like the most natural way to do what you want. A
HashMap
or even a simple sortedList
would be better.您不需要正则表达式来搜索已知字符串 - 只需使用
target.equals ("United Berkley")
。您可以通过确保您的 String[] 数组已排序来使自己更轻松 - 使用 Arrays.sort (...) 来保持它们的顺序,并使用 Arrays.binarySearch (...) 来快速搜索它们。不过,我确实质疑您的数据结构的布局 - 这似乎不是做您想做的事情的最自然的方式。
HashMap
甚至简单的排序List
似乎更合适。You don't need a regular expression to search for a known string - just use
target.equals ("United Berkley")
. You can make it easier on yourself by making sure that your String[] arrays are sorted - use Arrays.sort (...) to keep them in order and the use Arrays.binarySearch (...) to search them quickly.I do question the layout of your data structures though - it doesn't seem like the most natural way to do what you want. A
HashMap
or even a simple sortedList
seem more appropriate.