3

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)
}
1
  • 3
    Do you want to add elements to already existing list, or can we create and return new one? Does constructor like new Person(id, name) exist? Commented Feb 19, 2016 at 21:04

2 Answers 2

7

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());
Sign up to request clarification or add additional context in comments.

Comments

4

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.

4 Comments

This doesn't compile. And using 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.
yes it doesn't compile with foreach, I tried editing the answer but could not . Any specific drawbacks of using forEach ?
Apologies as I don't have access to a compiler right now... @Tunaki is right. You should avoid stateful lambdas especially when doing parallel stuff. This simple approach may only be accepted if the stream operation is serial.
This works, but using a stream in this way offers no benefit over the for loop. Streams are cool, but that doesn't mean we should replace all loops with streams.

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.