2011-07-18 132 views
0
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");' 

如果我有這個數組列表,並且我想搜索所有包含一個(即一,二十一和三十一)的字符串,我應該使用什麼邏輯?意味着我該怎麼做?Java搜索-Arraylist

+0

請讓我知道我們可以做到這一點... – rahul

回答

2
//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); 
    } 
} 
+0

謝謝Jigar,爲您的幫助! – rahul

+0

歡迎您:) –

3
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 
    } 
} 
+0

感謝您的幫助! – rahul

2
for (String word : words) { 
    if (word.contains("one")) { 
     //we have a match 
    } 
} 
+0

感謝您的幫助! – rahul

0

當然,你必須環通的元素。尋找通過ArrayList循環的方法:可以索引或用

for (x : collect) 

表示法。

在循環中,你必須做一些模式匹配。讀取字符串Java API文檔以獲取方法。

(Give'em一些人認爲食品...)

+0

感謝您的幫助! – rahul

0

你可以解決這個使用迭代器,如果條件將更爲複雜

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論證的結論或替代負責。

0

通常,在搜索List中的項目時,最好的解決方案是首先使用Collections.sort()方法對List進行排序。然後使用Collections.binarySearch()方法,找到你的元素。 在這種情況下,您的元素是String類型,它們是Comparable,可以按字母順序排序,否則您需要爲元素類類型實現Comparable接口。