Iterables.find and Iterators.find - instead of throwing exception, get null

StackOverflow https://stackoverflow.com/questions/2543052

  •  23-09-2019
  •  | 
  •  

문제

I'm using google-collections and trying to find the first element that satisfies Predicate if not, return me 'null'.

Unfortunately, Iterables.find and Iterators.find throws NoSuchElementException when no element is found.

Now, I am forced to do

Object found = null;
if ( Iterators.any( newIterator(...) , my_predicate )
{
    found = Iterators.find( newIterator(...), my_predicate )
}

I can surround by 'try/catch' and do the same thing but for my use-cases, I am going to encounter many cases where no-element is found.

Is there a simpler way of doing this?

도움이 되었습니까?

해결책

It sounds like you should be using Iterators.filter, then checking the value of hasNext on the returned iterator.

다른 팁

최상위 사이트의 하위 사이트에서 목록보기를 표시 할 수 있습니다. 이렇게하려면 다음을 수행해야합니다.

  • SharePoint Designer 에서 하위 사이트 열기
  • 라이브러리를 열고 목록보기 중 하나를 엽니 다.
  • LVWP를 선택하고 리본에서 웹 파트 리본 를 선택하십시오.
  • 명령을 사용하여 웹 파트를 "파일" 저장하십시오.
  • "예"를 사용하여 현재 목록에서 항상 목록 데이터를 항상 표시할지 여부 대화 상자에 응답합니다.
  • 변경 사항을 저장하지 않고 SharePoint Designer 닫기
  • 브라우저에서 최상위 사이트를 열고 웹 파트를 업로드
  • 이제 웹 파트를 구성하고보기를 편집 할 수 있습니다.

    이것은 Laura Rogers 911 블로그 2010 년에 일합니다. 2013 년에 시도하지 않았습니다.

    이 기술은 하위 사이트에서 최상위 사이트로 목록보기를 버블 링 할 수 있지만 하위 사이트에 최상위 레벨 목록보기를 표시하는 것은 작동하지 않습니다.

This was filed as a feature request:

http://code.google.com/p/guava-libraries/issues/detail?id=217

We are actually in progress on it.

I'm not sure if this qualifies as simpler, but at least it avoids exceptions and requires only one pass over the source iterable:

public static <T> T findMatchOrNull(Iterator<T> source, Predicate<T> pred) {
    Iterator<T> matching = Iterators.filter(source, pred);
    Iterator<T> padded = Iterators.concat(matching, Iterators.<T>singletonIterator(null));
    return padded.next();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top