[英]Convert List<Object> to String[] in Java
I need to convert from List<Object>
to String[]
.我需要从
List<Object>
转换为String[]
。
I made:我做了:
List<Object> lst ...
String arr = lst.toString();
But I got this string:但我得到了这个字符串:
["...", "...", "..."]
is just one string, but I need String[]只是一个字符串,但我需要 String[]
Thanks a lot.非常感谢。
You have to loop through the list and fill your String[]
.您必须遍历列表并填写您的
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])
;如果列表是
String
值,则列表就像调用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:您可以使用 toArray() 转换为对象数组,然后使用此方法将对象数组转换为字符串数组:
Object[] objectArray = lst.toArray();
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
Java 8 has the option of using streams like: Java 8 可以选择使用以下流:
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>
将包含String
集合,那么可以试试这个。
List<Object> lst = new ArrayList<Object>();
lst.add("sample");
lst.add("simple");
String[] arr = lst.toArray(new String[] {});
System.out.println(Arrays.deepToString(arr));
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));
There is a simple way available in Kotlin Kotlin 中有一个简单的方法
var lst: List<Object> = ...
listOFStrings: ArrayList<String> = (lst!!.map { it.name })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.