Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating objects with parameters in Java 8 Stream

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));
}
like image 632
Max Beaver Avatar asked Sep 01 '25 01:09

Max Beaver


1 Answers

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()));
like image 65
janos Avatar answered Sep 02 '25 22:09

janos