2011-07-18 5 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");' 

이 arraylist가 있고 하나의 문자열 (즉, 하나, 스물 한 개와 서른 개)이 포함 된 문자열을 검색하려면 어떤 논리를 사용해야합니까? 제가 어떻게해야합니까?자바 검색 - 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) 

표기법과 함께 사용할 수 있습니다.

루프에서 일부 패턴 일치를 수행해야합니다. 메서드의 String Java API doc를 읽습니다.

은 조건이

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"); 
       } 



      }; 
     } 

    } 

당신이 방법도 만들 수있는 하나의 조건을 더 확인하려면 더 복잡 될 경우

+0

도움 주셔서 감사합니다 !! – rahul

0

당신이 사용하는 반복자를 해결할 수 (... 약간의 음식을 생각 겁) 그것은 conuntion 또는 두 가지 IPredicate 인수의 대안을 담당합니다.

0

일반적으로 List에서 상품을 검색 할 때 가장 좋은 해결책은 방법을 사용하여 먼저 List을 정렬하는 것입니다. 그런 다음 Collections.binarySearch() 메소드를 사용하여 요소를 찾으십시오. 이 경우 String 유형은 Comparable이며 알파벳 순으로 정렬 할 수 있습니다. 그렇지 않으면 요소 유형으로 Comparable 인터페이스를 구현해야합니다.