Friday, 8 July 2016

How to convert List<Object> to List<String>

How to convert a List<Object> to List

This is a tricky situation that you may end up with sometimes.
Directly typecasting like shown below doesn't work:

List<String> stringList=(List<String>)objList;

Typecasting List<Object> to List<String> but it does not work as typecasting generic types is
not allowed. So this can be achieved by converting a List<Object> to an intermediate.
We can acheive this conversion in the following ways.

Typecasting the List itself as a simple Object and then to its generic type.

List<Object> objList=Arrays.asList("Hello", "World","CoderMagnet");
List<String> stringList=(List<String>)(Object)objList;

You can typecast through an intermediate wildcard.

List<Object> objList=Arrays.asList("Hello", "World","CoderMagnet");
List<String> stringList=(List<String>)(List<?>)objList;