4

Is it possible to create objects with parameters while using Stream class? I'd like to reproduce the following with Java 8 Stream.

for(Integer id:someCollectionContainingTheIntegers){
     someClass.getList().add(new Whatever(param1, id));
}

3 Answers 3

6

Sure. But if you have a collection, you can use forEach and a lambda:

someCollectionContainingTheIntegers.forEach(id -> someClass.getList().add(new Whatever(param1, id));

Another possible variation is to collect into the destination list:

someCollectionContainingTheIntegers.stream()
    .map(id -> new Whatever(param1, id))
    .collect(Collectors.toCollection(() -> someClass.getList()));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, Janos :)
2

One more solution...

    List<Whatever> collect = someCollectionContainingTheIntegers.stream()
            .map(id -> new Whatever(param1, id))
            .collect(toList());
    someClass.getList().addAll(collect);

Comments

1

do a foreach in the list

List<Integer> ml = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> ml2 = Arrays.asList(21, 22, 23, 24);
ml2.forEach(x -> ml.add(x));
System.out.println(ml);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.