Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert ArrayList<Object> to ArrayList<String>?

Tags:

java

arraylist

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

I tried:

ArrayList<String> list2 = (String)list;  

But it gave me a compile error.

like image 479
rtf Avatar asked Jan 03 '11 00:01

rtf


2 Answers

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

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

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

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

like image 175
BalusC Avatar answered Oct 09 '22 08:10

BalusC


It's not safe to do that!
Imagine if you had:

ArrayList<Object> list = new ArrayList<Object>(); list.add(new Employee("Jonh")); list.add(new Car("BMW","M3")); list.add(new Chocolate("Twix")); 

It wouldn't make sense to convert the list of those Objects to any type.

like image 25
athspk Avatar answered Oct 09 '22 08:10

athspk