I want to create a list (or collection in general) by calling a method x times. In Python it would be something like this.
self.generated = [self.generate() for _ in range(length)]
I tried to code something similar in JDK 8.
this.generated = IntStream.range(0, length)
.mapToObj(n -> this.generate())
.collect(Collectors.toList());
It works, but somehow it doesn't feel allright. Is there a more proper way of doing it?
Java 8 | Collectors counting() with ExamplesCollectors counting() method is used to count the number of elements passed in the stream as the parameter. It returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0.
I am not Python developer so I may misunderstood your example, but judging from Java example you may be looking for something like
Stream.generate(this::generate).limit(length).collect(Collectors.toList());
But as Brian Goetz mentioned your approach
IntStream.range(0, length).mapToObj(i->...)
will perform significantly better in parallel.
Not sure if this would feel any better to you, but here's one way to get the same effect:
Integer[] arr = new Integer[length];
Arrays.setAll(arr, n -> this.generate());
List<Integer> l = Arrays.asList(arr);
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