18

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.

calbertts
  • 1,482
  • 2
  • 15
  • 33

7 Answers7

27

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]);

Dan D.
  • 32,096
  • 5
  • 61
  • 79
  • 6
    Change `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. – Alexander Pogrebnyak Feb 08 '13 at 13:13
14

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);
Community
  • 1
  • 1
Steve Chambers
  • 34,055
  • 17
  • 142
  • 189
  • Why additional array copy when `objectArray` can still be used as String[]? – sundar Feb 08 '13 at 13:26
  • See the bottom part of the linked question - casting `objectArray` to `String[]` causes a `ClassCastException`. This answer explains better: http://stackoverflow.com/a/1018774/1063716 – Steve Chambers Feb 08 '13 at 13:33
  • Yes in case of List containing objects other than string. But that happens even in your code. – sundar Feb 08 '13 at 13:35
  • 3
    `List lst = new ArrayList(); lst.add(1);` I m getting ArrayStoreException for this test case. – sundar Feb 08 '13 at 13:38
10

Java 8 has the option of using streams like:

List<Object> lst = new ArrayList<>();
String[] strings = lst.stream().toArray(String[]::new);
akhil_mittal
  • 21,313
  • 7
  • 90
  • 91
5

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));
sundar
  • 1,740
  • 12
  • 28
2

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));
Srujan Kumar Gulla
  • 5,602
  • 9
  • 45
  • 77
2

Using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());
husayt
  • 13,559
  • 7
  • 48
  • 77
0

There is a simple way available in Kotlin

var lst: List<Object> = ...
    
listOFStrings: ArrayList<String> = (lst!!.map { it.name })
flaxel
  • 3,429
  • 4
  • 13
  • 26
Umasankar
  • 71
  • 1
  • 1