dbulgakov dbulgakov - 1 month ago 10
Java Question

Cast Object[] array into String[] array RxJava

I am trying to collect some property from list of objects into array using RxJava. I've wrote the code, but now I can't cast return type properly. So, I've tried this code:

Observable.just(rangeList)
.flatMap(Observable::from)
.map((range) -> String.format(Locale.getDefault(), "%s (%d)", range, range.getElementNumber()))
.cast(String.class)
.toList()
.toBlocking().first()
.toArray();


But it still returns Object[], and I need String[].

Answer

You could use the .toArray() parameter:

.toArray(new String[length]);

It is well described in the documentation:

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.