Search code examples
javagenericsjava-7type-conversionraw-types

How to convert List of raw data type to List<String> using Java 7(and below) only


There are a lot of QA posts on similar topics like:

Java: Converting lists of one element type to a list of another type

How to transform List to another List

However, all they use some additional libraries which is inappropriate in my case. I would like to find optimal solution using only Java 7 (and below) libs.

So let's say we've:

List list = new LinkedList(); 
list.add(2);
list.add("Mike");
list.add("John");
list.add(11);

transformer(list); // transform List to List<String>
list.get(0).toLowerCase(); 

How to implement void transform(List list) method ?


Solution

  • You'll need to return a new List<String>, and assign it. Iterate the input List, and call toString() on each element - adding that to a new List for returning. Something like,

    public static List<String> transformer(List list) {
        List<String> al = new ArrayList<String>();
        Iterator iter = list.iterator();
        while (iter.hasNext()) {
            al.add(iter.next().toString());
        }
        return al;
    }
    

    Then you can call it like

    List<String> stringList = transformer(list);
    stringList.get(0).toLowerCase();