0

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?

4
  • 1
    int is premitive and ArrayList can only hold objects like Integer, what are you trying to do ? and why do you need type casting ? Commented Dec 17, 2020 at 18:19
  • 1
    Does this answer your question? Convert Stream to IntStream Commented Dec 17, 2020 at 18:21
  • 1
    Using the word “generic” is confusing here. Do you mean Generics? If not, change your wording. Give a complete code example. Commented Dec 17, 2020 at 18:31
  • FYI: How do I get an IntStream from a List<Integer>? Commented Dec 17, 2020 at 18:39

1 Answer 1

2

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

“raw” is the technical term here, not “untyped”. ArrayList is itself a type. See tutorial.
Thank you! This was a more elegant/simple way of solving the problem :)
Cool, @BasilBourque, I've changed the variable name to reflect the terminology.
And your variable name in typed = should be something like parameterizedTyping = or castWithGenerics =.
You should not use Integer constructors, since they are deprecated.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.