我想要一个简单的方法来做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();
然后我做了一个concat:
Iterable<Portfolio> combined = Iterables.concat(result, result2);
但是当Jackson处理合并的Iterable时,它只显示{empty:false}而不是投资组合数组。
我看了Guava的concat实现。它基本上返回两个Iterables的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(Iterables列表)可能无法正常工作。有人能证实吗?感谢。
答案 0 :(得分:3)
您需要以下依赖项:
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。