Skip to content
Advertisement

Convert generic arraylist to non-generic using Java 8 Stream

I have some old code I’m trying to streamline:

ArrayList arr = (generic arraylist)
int[] newArr = new int[arr.size()];
for(int i=0; i<arr.size(); i++){
    newArr[i]=(int)arr.get(i);
}

I want to use the Java Stream API to simplify this. Here is my attempt:

ArrayList arr = (generic arraylist)
List<Integer> = arr.stream().map(m -> (int)m).collect(Collectors.toList());

My understanding is that it would iterate through arr, typecast every object m to an int, and then collect it into a List. But my compiler says that the right-hand-side of the second line returns and Object and not a List. Where am I going wrong?

Advertisement

Answer

Per your attempt, it looks like you want to map your ArrayList to an ArrayList<Integer>. The good news is, you don’t need to do any of this. The runtime type of ArrayList<Integer> is just ArrayList (this is called type erasure if you want to search for information about it). Only the compiler knows about the parameterized type.

So this code does what you want:

import java.util.ArrayList;

public class Cast {
    public static void main(String[] args) {
        //  This represents the ArrayList of Integer in your existing code
        ArrayList raw = new ArrayList(java.util.Arrays.asList(
            Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)
        ));

        //  You know what it is, so all you need to do is cast
        ArrayList<Integer> typed = (ArrayList<Integer>)raw;
        
        //  Still works; now recognized as list of integer
        for (Integer x : typed) {
            System.err.println(x);
        }
    }
}
Advertisement