Using Guava
List<Object> lst ...
List<String> ls = Lists.transform(lst, Functions.toStringFunction());
Lot of concepts here which will be useful:
List<Object> list = new ArrayList<Object>(Arrays.asList(new String[]{"Java","is","cool"}));
String[] a = new String[list.size()];
list.toArray(a);
Tip to print array of Strings:
System.out.println(Arrays.toString(a));
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);
There is a simple way available in Kotlin
var lst: List<Object> = ...
listOFStrings: ArrayList<String> = (lst!!.map { it.name })
Java 8 has the option of using streams like:
List<Object> lst = new ArrayList<>();
String[] strings = lst.stream().toArray(String[]::new);
If we are very sure that List<Object>
will contain collection of String
, then probably try this.
List<Object> lst = new ArrayList<Object>();
lst.add("sample");
lst.add("simple");
String[] arr = lst.toArray(new String[] {});
System.out.println(Arrays.deepToString(arr));
Source: Stackoverflow.com