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)
}
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());
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.
forEach is probably not a good idea: it is discouraged to use it in such cases. For example, if you run it in parallel, you would be surprised at the result.
new Person(id, name)exist?