java 如何将长数组转换为字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6609843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert long array to string array?
提问by Syed
I am getting the checked items ids in ListView
from List.getCheckedItemIds
which returns long
array, now how to convert this array to String
array ?
我正在ListView
从中获取已检查的项目 ID,从中List.getCheckedItemIds
返回long
数组,现在如何将此数组转换为String
数组?
long [] long_list = ProcessList.getCheckedItemIds();
回答by DeeV
String[] string_list = new String[long_list.length];
for(int i = 0; i < long_list.length; i++){
string_list[i] = String.valueOf(long_list[i]);
}
回答by Hank Chan
The question may be considered unwarranted a few years ago, but it's worth a new look now considering the recent progress in Java land with regards to the emerging Stream API.
几年前,这个问题可能被认为是没有根据的,但考虑到 Java 领域在新兴Stream API方面的最新进展,现在值得重新审视一下。
Instead of relying on any third-party API, you can use the built-in Stream APIfor array operations in Java 1.8 and above.
在 Java 1.8 及更高版本中
,您可以使用内置的Stream API进行数组操作,而不是依赖任何第三方 API 。
You can now easily use
您现在可以轻松使用
String[] yourStringArray = Arrays.stream(yourLongArray).mapToObj(String::valueOf).toArray();
And if your intention is to print yourStringArray
, you can then convert it into a string using
如果您打算打印yourStringArray
,则可以使用以下方法将其转换为字符串
String str = Arrays.toString(yourStringArray);
****
Lucky for us, Arrays.toString()
operates on all types of arrays, so the whole thing can be simplified to just
****
幸运的是,我们可以Arrays.toString()
对所有类型的数组进行操作,因此整个过程可以简化为
String str = Arrays.toString(yourLongArray);
Isn't this cleaner?
这不是更清洁吗?
回答by marvedly
Or with Java 8+,
或者使用 Java 8+,
Object[] array = ...; // or i.e. Long[] array
String[] s = Arrays.stream(array).map(String::valueOf).toArray(String[]::new);
回答by albertoja
You can use org.apache.commons.lang.StringUtilslike this:
您可以像这样使用org.apache.commons.lang.StringUtils:
String[] string_list = StringUtils.join(long_list, ",").split(",");
回答by Frank Zhang
You can leverage apache's BeanUtils to do Array conversion without doing iteration by yourself like below.
您可以利用 apache 的 BeanUtils 进行数组转换,而无需像下面这样自己进行迭代。
Long[] longArrays= (Long[]) ConvertUtils.convert(stringArrays, Long[].class);
回答by Sumit
You can make a new String array and pass the values of long array to the string array one by one:
可以新建一个String数组,将long数组的值一一传递给字符串数组:
String[] s=new String[long_list.length];
for(int i=0;i<long_list.length;i++)
{
s[i]=String.valueOF(long_list[i]);
}
Sorry for the mistakes. I've updated the code.
对错误表示抱歉。我已经更新了代码。