java – Using Java8 Stream to create a list of objects from another

You could create a method that turns two collections into a new collection, like this:

public  Collection singleCollectionOf(final Collection collectionA, final Collection collectionB, final Supplier> supplier, final BiFunction mapper) {
    if (Objects.requireNonNull(collectionA).size() != Objects.requireNonNull(collectionB).size()) {
        throw new IllegalArgumentException();
    }
    Objects.requireNonNull(supplier);
    Objects.requireNonNull(mapper);
    Iterator iteratorA = collectionA.iterator();
    Iterator iteratorB = collectionB.iterator();
    Collection returnCollection = supplier.get();
    while (iteratorA.hasNext() && iteratorB.hasNext()) {
        returnCollection.add(mapper.apply(iteratorA.next(), iteratorB.next()));
    }
    return returnCollection;
}

The important part here is that it will map iteratorA.next() And iteratorB.next() obtained in a new object.

It is called like this:

List list1 = IntStream.range(0, 10).boxed().collect(Collectors.toList());
List list2 = IntStream.range(0, 10).map(n -> n * n + 1).boxed().collect(Collectors.toList());
singleCollectionOf(list1, list2, ArrayList::new, Pair::new).stream().forEach(System.out::println);

In your example it would be:

List lst3 = singleCollectionOf(lst1, lst2, ArrayList::new, ObjectType3::new);

Where for example Pair::new is a shortcut to lamdda (t, u) -> new Pair(t, u).

Leave a comment