I'm trying to initialize random 5 elements(Object) and I'm trying to use Stream.iterate function but something it's wrong first element(object) always is null.
Stream.iterate(new Student(), s -> {
s.setId(new Random().nextInt(5));
s.setUsername(UUID.randomUUID().toString());
s.setPassword(UUID.randomUUID().toString());
return s;
}).limit(5)
.forEach(System.out::println);
Output:
Student{id=null, username=null, password=null}
Student{id=0, username=7d7403e0-89f0-4033-a874-31e0aae1d7c6, password=590baa12-a9f7-4fef-8a47-4bcb7f2174d1}
Student{id=3, username=d75bff67-a1f7-4969-9418-93f3e0eb1cd7, password=9e48d614-a15e-4f2a-9e87-63ed3a81f410}
Student{id=3, username=47943516-e8bd-4ffe-bc47-4e251104994a, password=f2d4d02d-2e37-4346-a51d-b83f40044c68}
Student{id=2, username=1a1e5f9e-7fac-439f-b5f2-2931884e0772, password=9df36248-5e1e-4b28-b1c0-020123dd26b8}
What is wrong here?
As a complement to the given answer: using iterate
the way you do, you actually create only one instance of Student
that you keep mutating.
It is fine as long you consume each element of the stream with the forEach
method. If you collected your stream in a List
, you would get a list of 5 times the same element after having applied the last mutation.
If you want to create several instances, use generate
:
Stream.generate(() -> new Student(new Random().nextInt(5),
UUID.randomUUID().toString(),
UUID.randomUUID().toString()))
.limit(5)
.forEach(System.out::println);
The first element in what Stream.iterate()
returns is the seed element, i.e. the new Student() you provided. See the javadoc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With