Using Java8 Streams to create a list of objects from another two lists

前端 未结 3 1616
执笔经年
执笔经年 2020-12-14 19:13

I have the following Java6 and Java8 code:

List lst1 = // a list of ObjectType1 objects
List lst2 = // a list of Object         


        
3条回答
  •  执笔经年
    2020-12-14 19:54

    You could create a method that transforms 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 the obtained iteratorA.next() and iteratorB.next() into 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 shorthand for the lamdda (t, u) -> new Pair(t, u).

提交回复
热议问题