我如何转换的ArrayList<对象>到ArrayList的<串GT ;? [英] How can I convert ArrayList<Object> to ArrayList<String>?

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

问题描述

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 -> (object != null ? object.toString() : null))
   .collect(Collectors.toList());

或者,当你不基于Java 8尚未:

Or when you're not on Java 8 yet:

List<String> strings = new ArrayList<>();
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&LT;对象&gt;到ArrayList的&LT;串GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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