如何转换 ArrayList<Object>到 ArrayList<String>? [英] How can I convert ArrayList&lt;Object&gt; to ArrayList&lt;String&gt;?

查看:34
本文介绍了如何转换 ArrayList<Object>到 ArrayList<String>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayList<Object> list = new ArrayList<Object>();
list.add(1);
list.add("Java");
list.add(3.14);
System.out.println(list.toString());

我试过:

ArrayList<String> list2 = (String)list; 

但它给了我一个编译错误.

But it gave me a compile error.

推荐答案

由于这实际上不是字符串列表,最简单的方法是遍历它并将每个项目转换为新列表自己的字符串:

Since this is actually not a list of strings, the easiest way is to loop over it and convert each item into a new list of strings yourself:

List<String> strings = list.stream()
   .map(object -> Objects.toString(object, null))
   .collect(Collectors.toList());

或者当您尚未使用 Java 8 时:

Or when you're not on Java 8 yet:

List<String> strings = new ArrayList<>(list.size());
for (Object object : list) {
    strings.add(Objects.toString(object, null));
}

或者当您尚未使用 Java 7 时:

Or when you're not on Java 7 yet:

List<String> strings = new ArrayList<String>(list.size());
for (Object object : list) {
    strings.add(object != null ? object.toString() : null);
}

请注意,您应该针对接口声明 (java.util.List 在这种情况下),而不是实现.

Note that you should be declaring against the interface (java.util.List in this case), not the implementation.

这篇关于如何转换 ArrayList<Object>到 ArrayList<String>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆