java - 如何以惰性方式连接java中的两个集合?

标签 java lazy-loading iterable enumerable

我有两个集合,我想返回一个 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/

相关文章:

java - spring 序列化类中的每个属性(延迟加载?)

javascript - 延迟加载 Google API 不起作用

java迭代器/可迭代子接口(interface)

python - 如何生成一个列表,其中的元素与所需列表的距离固定

java - JFrame 在第一次实例化后不工作?

java - 如何在选择菜单项后启用recyclerview OnItemClickListener?

java - 如何使用 JUnit 与 Spring 和 Hibernate 来模拟事务的结束以隔离 LazyInitializationException?

Java Iterables "Resetting"带有每个 Foreach 构造的迭代器

c# - 为什么 ValueTypes 在像 C#、Java 这样的面向对象语言中

java - 确定偏移量是否在行号之间?