Try it like this. Just omit the generic type in the toArray
method. The suppress warnings removes the compiler's type safety warning (you may get a runtime class cast exception if the resulting types don't match since the types are erased). But in this case, it isn't a problem.
List<List<String>> results = new ArrayList<>(
List.of(List.of("ABC", "DEF"), List.of("GHI", "JKL")));
@SuppressWarnings("unchecked")
List<String>[] array = results.stream().toArray(List[]::new);
for (List<String> lst : array) {
System.out.println(lst);
}
String a = array[0].get(1);
System.out.println(a);
prints
[ABC, DEF]
[GHI, JKL]
DEF
Contrast the following using the same data and see what happens when you try to get an "Integer"
from a list in the array.
@SuppressWarnings("unchecked")
List<Integer>[] array = results.stream().toArray(List[]::new);
Integer a = array[0].get(1); // class cast exception!!
System.out.println(a);
And finally, you can also do it sans streams.
@SuppressWarnings("unchecked")
List<String>[] arr = new ArrayList[2];
arr[0] = new ArrayList<>(List.of("ABC","DEF"));
arr[1] = new ArrayList<>(List.of("GHI","JKL"));
String a = arr[1].get(0);
System.out.println(a);
prints
GHI
>`? More, err, generic that way.
– user207421 Jun 26 '23 at 03:51> to List?
– Gaurav Jeswani Jun 26 '23 at 04:09> to an array of List, this are two cases to demonstrate my question.
– Tom Jun 26 '23 at 04:20