Skip to content
Advertisement

Convert generic arraylist to non-generic using Java 8 Stream

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

JavaScript

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

JavaScript

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:

JavaScript
Advertisement