Reputation: 838
Is there a java 8 way of doing the following?
for(int i;i<=100;i++){
Person person=new Person();
person.setId(i);
person.setName("name"+i);
list.add(person)
}
Upvotes: 3
Views: 219
Reputation: 72844
Yes:
IntStream.rangeClosed(0, 100)
.forEach(i -> {
Person person=new Person();
person.setId(i);
person.setName("name"+i);
list.add(person);
});
EDIT:
As commented below, accessing an existing list inside the lambda expression parameter of the stream operation goes against functional programming. It's better to do:
List<Person> persons = IntStream.rangeClosed(0, 100)
.mapToObj(i -> {
Person person=new Person();
person.setId(i);
person.setName("name" + i);
return person;
})
.collect(Collectors.toList());
See https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html.
Upvotes: 4
Reputation: 137084
You can obtain a list of persons by mapping each int
from 0 to 100 into a Person
.
List<Person> persons = IntStream.rangeClosed(0, 100).mapToObj(i -> {
Person person = new Person();
person.setId(i);
person.setName("name" + i);
return person;
}).collect(Collectors.toList());
Then, you can append that persons
list into an existing one for example.
IntStream.rangeClosed
return a IntStream
of primitive int
. Each is mapped to the object Person
with mapToObj
and collected into a list with Collectors.toList()
.
It would be cleaner if you had a constructor of Person
taking the id and the name. With such a constructor, you could write:
List<Person> persons = IntStream.rangeClosed(0, 100)
.mapToObj(i -> new Person(i, "name" + i))
.collect(Collectors.toList());
Upvotes: 7