Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a list of given length in Java 8?

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?

like image 832
Radosław Łazarz Avatar asked May 19 '14 23:05

Radosław Łazarz


People also ask

How do you count elements in a list in Java 8?

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.


2 Answers

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.

like image 164
Pshemo Avatar answered Sep 28 '22 04:09

Pshemo


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);
like image 42
ajb Avatar answered Sep 28 '22 06:09

ajb