iterable。找到和迭代器。查找——而不是抛出异常,得到null。

时间:2020-12-03 20:48:32

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

我使用google-collection,并尝试找到满足谓词的第一个元素,如果不是,返回“null”。

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

不幸的是,iterable。找到和迭代器。当没有找到元素时,查找抛出NoSuchElementException。

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.

我可以用“try/catch”来做同样的事情,但是对于我的用例,我将遇到很多没有找到元素的情况。

Is there a simpler way of doing this?

有没有更简单的方法?

4 个解决方案

#1


5  

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

听起来你应该使用迭代器。过滤器,然后在返回的迭代器上检查hasNext的值。

#2


12  

Since Guava 7, you can do this using the Iterables.find() overload that takes a default value:

由于Guava 7,您可以使用Iterables.find()重载,它具有默认值:

Iterables.find(iterable, predicate, null);

#3


2  

This was filed as a feature request:

这是作为一个特性请求提出的:

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

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

We are actually in progress on it.

我们实际上正在取得进展。

#4


0  

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

#1


5  

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

听起来你应该使用迭代器。过滤器,然后在返回的迭代器上检查hasNext的值。

#2


12  

Since Guava 7, you can do this using the Iterables.find() overload that takes a default value:

由于Guava 7,您可以使用Iterables.find()重载,它具有默认值:

Iterables.find(iterable, predicate, null);

#3


2  

This was filed as a feature request:

这是作为一个特性请求提出的:

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

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

We are actually in progress on it.

我们实际上正在取得进展。

#4


0  

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