I am trying to convert a List of type Integer to an Array of Strings. I want to do it using the method reference passed to toArray() as below, which must work somehow since my CS professor showed this to us in class.
List<Integer> strawberry = IntStream.rangeClosed(1, 100)
.boxed().collect(Collectors.toList());
String[] plum = strawberry.toArray(String[]::new);
However I got the following error message:
Exception in thread "main" java.lang.ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.lang.String at java.base/java.lang.System.arraycopy(Native Method)
How can this be fixed?
I know there are easier ways of doing this, but I want to learn how to use this method correctly. Thanks.
You need to first map to a string stream:
String[] plum = strawberry.stream()
.map(String::valueOf)
.toArray(String[]::new);
But you can do both in one step:
String[] plum = IntStream.rangeClosed(1, 100)
.mapToObj(String::valueOf)
.toArray(String[]::new);
One you need both stream
and valueOf
from `String:
List<Integer> strawberry = IntStream.rangeClosed(1, 100)
.boxed().collect(Collectors.toList());
String[] plum = strawberry.stream().map(String::valueOf).toArray(String[]::new);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.