How to convert object array to string array in Java
To convert an object array to a string array in Java, you can use the toString() method of the Object class and the map() method of the Stream class.
To convert an object array to a string array in Java, you can use the toString() method of the Object class and the map() method of the Stream class.
Here is an example of how you can convert an object array to a string array in Java:
import java.util.Arrays;
Object[] objectArray = {"item1", "item2", "item3"};
String[] stringArray = Arrays.stream(objectArray)
.map(String::valueOf)
.toArray(String[]::new);In this example, the objectArray is declared as Object[] but contains String elements. The Arrays.stream() method creates a stream from the array. The map() method applies String::valueOf to each element, which safely handles null values by converting them to the string "null". Finally, toArray() collects the results into a String[].
You can also use the Arrays.asList() method to convert the object array to a List and then use the toArray() method to convert the List to an array:
import java.util.Arrays;
Object[] objectArray = {"item1", "item2", "item3"};
String[] stringArray = Arrays.asList(objectArray).toArray(new String[0]);Note: This approach assumes all elements in the Object[] are already String instances. If the array contains other types, it will throw an ArrayStoreException at runtime. For safer and more flexible conversion, the Stream approach above is recommended.
I hope this helps! Let me know if you have any questions.