简体   繁体   English

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

[英]Check if ArrayList<String> contains part of a string

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'); 我希望在我说arrayList.containsSubString('string1');时返回arrayList的第一个元素。 How could this be done other than iterating through each of the elements of the arrayList and checking if string1 is a substring of that element string? 除了遍历arrayList每个元素并检查string1是否是该元素字符串的子字符串之外, arrayList

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. 不知道这是否被认为是好的做法。

With an ArrayList there is no other option than iterating through it. 对于ArrayList,除了对其进行遍历之外没有其他选择。 But you could use other data structures like a prefix tree (eg a ternary search tree , see this java sample ). 但是您可以使用其他数据结构,例如前缀树(例如三元搜索树 ,请参阅此Java示例 )。

Can't. 不行 Even if there was an equivalent of List.contains() it just does a linear search under the hood. 即使存在List.contains()的等效项,它也只能在后台进行线性搜索。

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)查找给定集合中与给定谓词匹配的第一个元素。

You can use a NavigableSet 您可以使用NavigableSet

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM