I have an array of ints that I want to use to instantiate a array or list of objects. In my case, the old-fashoned way to do it would be:
int[] layer_sizes = {784, 500, 10};
Layer[] layers = new Layer[layer_sizes.length];
for (int i=0; i<layer_sizes.length; i++)
layers[i] = new Layer(layer_sizes[i]);
But now I see Java 8 has all these fancy streams. I now want to do something like Python's list comprehensions:
List<Layer> layers = Stream.of(layer_sizes).map(size -> Layer(size));
But it doesn't let me do that, and I'm not sure why... The message it gives is
incompatible types: no instance(s) of type variable(s) R exist so that Stream<R> comforms to List<Layer> where R, T are type variables....
Is there a way to use Streams to construct an array of objects in one line?
EDIT: Not a duplicate of previous question, because it turns out that there're some peculiarities of making streams from primitives.
Conclusion
Thank you Sam Sun and Eran. The line I ended up using was this:
Layer[] layers = Arrays.stream(layer_sizes).boxed().map(Layer::new).toArray(Layer[]::new);
Whatever boxed() is, you need it, unless you declare layer_sizes as an Integer
instead of int
.
P.S. If the java developers are reading this, it would be amazing for Java 9 or whatever's next to have something like
Layer[] layers = {new Layer(size) for (size:layer_sizes)} // OR at least:
Layer[] layers = Stream.of(layer_sizes).map(Layer::new).toArray()