Guava Iterables concat 实现不适用于 Java 8 中添加的新 Iterable API 方法?

Guava Iterables concat implementation does not work with new Iterable API methods added in Java 8?

我想要一种简单的方法来执行 Iterables concat,所以我在我的 Spring MVC 代码 (Spring 4.2.1) 中尝试了 Guava Iterables (19 RC1)。

我有两个来自 Spring Data JPA 的迭代器。例如

Iterable<Portfolio> result = portfRepository.findBySomeCriteria();
Iterable<Portfolio> result2 = portfRepository.findByOtherCriteria();

然后我做一个连接:

Iterable<Portfolio> combined = Iterables.concat(result, result2);

然而,当组合的 Iterable 被 Jackson 处理时,它只显示 { empty: false } 而不是投资组合数组。

我查看了 Guava 的 concat 实现。它基本上 return 一个包含两个 Iterable 的 ImmutableList,并提供了一个重写的 Iterator,它知道如何遍历第一个 Iterable,然后是第二个 Iterable。

/**
 * Combines two iterables into a single iterable. The returned iterable has an
 * iterator that traverses the elements in {@code a}, followed by the elements
 * in {@code b}. The source iterators are not polled until necessary.
 *
 * <p>The returned iterable's iterator supports {@code remove()} when the
 * corresponding input iterator supports it.
 */
public static <T> Iterable<T> concat(
  Iterable<? extends T> a, Iterable<? extends T> b) {
  return concat(ImmutableList.of(a, b));
}

/**
 * Combines multiple iterables into a single iterable. The returned iterable
 * has an iterator that traverses the elements of each iterable in
 * {@code inputs}. The input iterators are not polled until necessary.
 *
 * <p>The returned iterable's iterator supports {@code remove()} when the
 * corresponding input iterator supports it. The methods of the returned
 * iterable may throw {@code NullPointerException} if any of the input
 * iterators is null.
 */
public static <T> Iterable<T> concat(
  final Iterable<? extends Iterable<? extends T>> inputs) {
  checkNotNull(inputs);
  return new FluentIterable<T>() {
    @Override
    public Iterator<T> iterator() {
      return Iterators.concat(iterators(inputs));
    }
  };
}

问题是,Java 8 Iterable API 提供了新的方法:

default void forEach(Consumer<? super T> action)
default Spliterator<T> spliterator()

我想如果某些代码(在本例中为 Spring MVC 或 Jackson)使用这些方法来循环遍历 Iterable 而不是迭代器方法,那么串联的 Guava Iterable 就是一个 Iterable 列表可能行不通。有人可以证实这一点吗?谢谢。

您需要以下依赖项:

This adds support for Guava specific datatypes.

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-guava</artifactId>
    <version>2.6.2</version>
</dependency>

您可能在某些时候也需要 JDK8 datatypes