I want to populate an array using generic lists as elements using Provider and Stream.generate.
Looks like:
Supplier<List<Object>> supplier = () -> new ArrayList<Object>(); List<Object>[] test = (List<Object>[]) Stream.generate(supplier).limit(m).toArray();
With the output of Error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.util.List;
Now, how can I populate an array using a generic type using the methods provided by Java 8? Or is it just not possible (yet), and should I do it in a "classic" way?
Regards, Claas M
EDIT
In response to a @Water query, I tested several performance tests with filling out arrays / lists using stream.collect (with casting testing arrays) and the traditional iteration method.
First, performance tests using lists:
private static int m = 100000; public static void main(String[] args) { Supplier<String> supplier = () -> new String(); long startTime,endTime;
And secondly, performance tests using arrays:
private static int m = 100000000; public static void main(String[] args) { Supplier<String> supplier = () -> new String(); long startTime,endTime;
As you can see, Water really was right - Cast makes it slower. But for lists, the new method is faster; at least 100k - 1M elements. I still donβt know why its much slower when it comes to 10M Elements, and I would love to hear some comments about this.
java arrays generics lambda
Claas M.
source share