ArrayList
Your code ArrayList<String> list2 = (String)list;
does not compile because list2
is not of type String
. But that is not the only problem.
You can use wildcard to do this as following
ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);
A simple solution:
List<Object> lst =listOfTypeObject;
ArrayList<String> aryLst = new ArrayList<String>();
for (int i = 0; i < lst.size(); i++) {
aryLst.add(lst.get(i).toString());
}
Note: this works when the list contains all the elements of datatype String.
Using guava:
List<String> stringList=Lists.transform(list,new Function<Object,String>(){
@Override
public String apply(Object arg0) {
if(arg0!=null)
return arg0.toString();
else
return "null";
}
});
Using Java 8 you can do:
List<Object> list = ...;
List<String> strList = list.stream()
.map( Object::toString )
.collect( Collectors.toList() );