Guava 中 Iterables.tryFind 和 FluentIterable.firstMatch 的区别

Difference between Iterables.tryFind and FluentIterable.firstMatch in Guava

有什么区别吗?

MyObject myWantedObj = Iterables.tryFind(myListOfObjects, new Predicate<MyObject>() {
    public boolean apply(MyObject myObj) {
        return myObj.getSomeAttribute().equals(someFinalVariable);
    }
}).orNull();

MyObject myWantedObj = FluentIterable.from(myListOfObjects).firstMatch(new Predicate<MyObject>() {
    public boolean apply(MyObject myObj) {
        return myObj.getSomeAttribute().equals(someFinalVariable);
    }
}).orNull();

Iterables.tryFind and FluentIterable.firstMatch Javadoc 等于:

Returns an Optional containing the first element in iterable that satisfies the given predicate, if such an element exists.

我错过了什么?

Iterables.tryFind()FluentIterable.firstMatch() 早了很多。如果你只是做一个单一的操作(如你的例子),那么你使用哪个并不重要。如果我们先创建 FluentIterable(事后看来是 20/20),我们可能永远不会创建 Iterables class。

当您将多个功能类型的步骤链接在一起时,FluentIterable 的威力就会显现出来。例如:

   FluentIterable
       .from(database.getClientList())
       .filter(activeInLastMonth())
       .transform(Functions.toStringFunction())
       .limit(10)
       .toList();