创建FluentIterable链作为函数,而不是立即应用

时间:2015-01-23 14:45:24

标签: java collections functional-programming guava

有没有办法创建FluentIterable函数链,但延迟绑定到特定集合?

例如:

Function<Collection<T>, T> chooseBy(Function<T, KEY> transform, KEY compare) {
    return FluentIterable.transform(transform).first(Predicates.equalTo(compare)).get();
}

1 个答案:

答案 0 :(得分:1)

不是直接,但你可以自己创建Function<Collection<T>, U>(注意它实际上转换为U):

public static <T, U> Function<Collection<T>, U> chooseBy(final Function<T, U> transform,
                                                         final U compare) {
    return new Function<> {
        @Override
        public U apply(Collection<T> input) {
            return FluentIterable.from(input)
                    .transform(transform)
                    .firstMatch(Predicates.equalTo(compare))
                    .get();
        }
    }
}

如果你真的想要Function<Collection<T>, T>,那就是

public static <T, U> Function<Collection<T>, T> chooseBy(final Function<T, U> transform,
                                                         final U compare) {
    return new Function<> {
        @Override
        public U apply(Collection<T> input) {
            return FluentIterable.from(input)
                    .firstMatch(
                            Predicates.compose(Predicates.equalTo(compare), transform))
                    .get();
        }
    }
}