java 检查 ArrayList<String> 是否包含字符串的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6428005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:50:59  来源:igfitidea点击:

Check if ArrayList<String> contains part of a string

javaarraylist

提问by TookTheRook

Say I have an ArrayList:

假设我有一个 ArrayList:

<string1.4>
<string2.4>
<string3.4>

and I wish to return the the first element of the arrayList when I say arrayList.containsSubString('string1'); How could this be done other than iterating through each of the elements of the arrayListand checking if string1is a substring of that element string?

当我说 arrayList.containsSubString('string1'); 时,我希望返回 arrayList 的第一个元素;除了遍历 的每个元素arrayList并检查是否string1是该元素字符串的子字符串之外,如何做到这一点?

回答by aioobe

The only way I can think of is doing something like:

我能想到的唯一方法是做类似的事情:

strs.get(strs.indexOf(new Object() {
    @Override
    public boolean equals(Object obj) {
        return obj.toString().contains(s);
    }
}));

Don't know if it is considered good practice though.

不知道这是否被认为是好的做法。

回答by morja

With an ArrayList there is no other option than iterating through it. But you could use other data structures like a prefix tree (e.g. a ternary search tree, see this java sample).

对于 ArrayList,除了遍历它之外别无选择。但是您可以使用其他数据结构,例如前缀树(例如三元搜索树,请参阅此java 示例)。

回答by jiggy

Can't. Even if there was an equivalent of List.contains() it just does a linear search under the hood.

不能。即使有一个等效的 List.contains() 它只是在引擎盖下进行线性搜索。

回答by Ralph

I think iterating though the list and checking each item is the fastest way. And it is also the way every one understand your code. (except of building your own data structure).

我认为遍历列表并检查每个项目是最快的方法。这也是每个人理解你的代码的方式。(除了构建自己的数据结构)。



Anyway you can also use org.apache.commons.collections.CollectionUtils#find(Collection, Predicate)

无论如何你也可以使用 org.apache.commons.collections.CollectionUtils#find(Collection, Predicate)

find(java.util.Collection collection, Predicate predicate)Finds the first element in the given collection which matches the given predicate.

find(java.util.Collection collection, Predicate predicate)查找给定集合中与给定谓词匹配的第一个元素。

回答by Peter Lawrey

You can use a NavigableSet

您可以使用 NavigableSet

NavigableSet<String> set = new TreeSet<String>();
// add strings

String find =
String firstMatch = set.ceiling(find);