我有两个集合,我想返回一个 IEnumerable,它是它们的串联。返回的枚举应该是惰性的,不应该修改两个初始集合(所以,我不想将两个集合复制到一个然后返回结果,因为那不是惰性的)
下面的代码是我想用 Java 实现但用 c# 编写的示例:
public static IEnumerable<int> all()
{
List<int> list1 = new List<int>() { 1, 2, 3 };
List<int> list2 = new List<int>() { 4, 5, 6 };
return list1.Concat(list2);
}
最佳答案
您可以使用 Apache Commons Collections方法 IterableUtils.chainedIterable(list1, list2)
:
Combines the provided iterables into a single iterable.
The returned iterable has an iterator that traverses the elements in the order of the arguments, i.e. iterables[0], iterables2, .... The source iterators are not polled until necessary.
或Guava方法 Iterables.concat(list1, list2)
:
Combines multiple iterables into a single iterable. The returned iterable has an iterator that traverses the elements of each iterable in inputs. The input iterators are not polled until necessary.
关于java - 如何以惰性方式连接java中的两个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182108/