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.


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

4

7 回答 7

27

您必须遍历列表并填写您的String[].

String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
  array[index] = (String) value;
  index++;
}

如果列表是String值,List 那么这将像调用一样简单lst.toArray(new String[0])

于 2013-02-08T13:08:49.820 回答
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);
于 2013-02-08T13:12:36.353 回答
10

Java 8 has the option of using streams like:

List<Object> lst = new ArrayList<>();
String[] strings = lst.stream().toArray(String[]::new);
于 2015-06-23T12:06:27.553 回答
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));
于 2013-02-08T13:22:41.647 回答
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));
于 2013-02-08T19:05:49.753 回答
2

Using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());
于 2013-07-17T13:13:13.137 回答
0

There is a simple way available in Kotlin

var lst: List<Object> = ...
    
listOFStrings: ArrayList<String> = (lst!!.map { it.name })
于 2021-02-11T13:05:53.793 回答