I need to convert from List<Object>
to String[]
.
I made:
List<Object> lst ...
String arr = lst.toString();
But I got this string:
["...", "...", "..."]
is just one string, but I need String[]
Thanks a lot.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
The toString() method on a list returns a string that is surrounded by square brackets and has commas between items. The idea is to get rid of square brackets using the substring() method and comma and space replace using the replaceAll() method.
In Java, a string is an object that represents a number of character values. Each letter in the string is a separate character value that makes up the Java string object. Characters in Java are represented by the char class. Users can write an array of char values that will mean the same thing as a string.
You have to loop through the list and fill your String[]
.
String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
array[index] = (String) value;
index++;
}
If the list would be of String
values, List then this would be as simple as calling lst.toArray(new String[0])
;
You could use toArray() to convert into an array of Objects followed by this method to convert the array of Objects into an array of Strings:
Object[] objectArray = lst.toArray();
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With