Search code examples
javalazy-loadingiterableenumerable

How to concatenate two collections in java in a lazy way?


I have two collections and I want to return an IEnumerable which is the concatenation of them. The returned enumerable should be lazy and should not modify the two initial collections (So, I do not want to copy the two collection into one and then return the result because that is not lazy)

The code below is an example of what I want to achieve in Java but written in 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);
}

Solution

  • A Java equivalent of the C# IEnumerable<TSource> Enumerable.Concat<TSource>(IEnumerable<TSource>, IEnumerable‌​<TSource>) can be found in Commons Collections: <E> Iterable<E> IterableUtils.chainedIterable(Iterable<? extends E> a, Iterable<? extends E> b). Look it up.