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.
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.
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]);
array[index] = (String) value, to array[index] = String.valueOf( value ). The answer as it is will crash if the list contains anything, but Strings. Maybe this is what OP wants.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);
objectArray can still be used as String[]?objectArray to String[] causes a ClassCastException. This answer explains better: stackoverflow.com/a/1018774/1063716List<Object> lst = new ArrayList<Object>(); lst.add(1); I m getting ArrayStoreException for this test case.Java 8
Java 8 has the option of using streams as well.
List<Object> lst = new ArrayList<>();
lst.add("Apple");
String[] strings = lst.stream().toArray(String[]::new);
System.out.println(Arrays.toString(strings)); // [Apple]
If we have a stream of Object, we would need an intermediate operation to do object-to-string conversion, and a terminal operation to collect the results. We can use Objects.toString(obj, null) or any other such implementation for string conversion.
String[] output = lst.stream()
.map((obj) -> Objects.toString(obj, null))
.toArray(String[]::new);
Using Guava
List<Object> lst ...
List<String> ls = Lists.transform(lst, Functions.toStringFunction());