[英]Java search-Arraylist
ArrayList searchList = new ArrayList();
ArrayList words=(ArrayList) request.getSession().getAttribute("words");
words.add("one");
words.add("twenty one");
words.add("thirty one");
words.add("two");
words.add("twenty two");
words.add("thirty two");
words.add("three");
words.add("twenty three");
words.add("thirty three");'
如果我有這個 arraylist 並且我想搜索所有包含 1 的字符串(即 1、21 和 31),我應該使用什么邏輯? 意味着我應該怎么做?
for (String item : searchList) {
if (item.contains("one") {
// Do something. Like adding the result to a different list.
// If you need the index from the original list, you a for instead of a for each
}
}
//iterate through words
for(String str : list){
//check if word contains the key
if(str.contains(key)){
//add its reference to another resultant list
result.add(str);
}
}
for (String word : words) {
if (word.contains("one")) {
//we have a match
}
}
通常,在List
中搜索項目時,最好的解決方案是首先使用Collections.sort()
方法對List
進行排序。 然后使用Collections.binarySearch()
方法,找到你的元素。 在這種情況下,您的元素是可Comparable
的String
類型,並且可以按字母順序排序,否則您需要為您的元素 class 類型實現Comparable
接口。
當然,您必須遍歷元素。 尋找通過 ArrayList 循環的方法:可以索引或使用
for (x : collect)
符號。
在循環中,您必須進行一些模式匹配。 閱讀字符串 Java API 文檔以獲取方法。
(給他們一些思考的食物......)
如果條件更復雜,您可以使用迭代器解決此問題
public interface IPredicate<T> {
boolean check(T t);
}
public class PredicatIterable<T> implements Iterable<T> {
private final Iterator<T> iterator;
private final IPredicate<T> predicate;
public PredicatIterable(Iterable<T> iterable, IPredicate<T> predicate) {
this.iterator = iterable.iterator();
this.predicate = predicate;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
T current;
@Override
public boolean hasNext() {
if(iterator.hasNext()) {
T next = iterator.next();
if(predicate.check(next)) {
current = next;
return true;
}
current = null;
}
return false;
}
@Override
public T next() {
return current;
}
@Override
public void remove() {
throw new RuntimeException("Invalid useage of method");
}
};
}
}
要驗證更多單個謂詞,您還可以創建負責連接或替代兩個 IPredicate 參數的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.