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?

Anthony
  • 311
  • 1
  • 3
  • 13
  • 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 ? – Ryuzaki L Dec 17 '20 at 18:19
  • 1
    Does this answer your question? [Convert Stream to IntStream](https://stackoverflow.com/questions/28015278/convert-stream-to-intstream) – Omar Abdel Bari Dec 17 '20 at 18:21
  • 1
    Using the word “generic” is confusing here. Do you mean [Generics](https://en.m.wikipedia.org/wiki/Generics_in_Java)? If not, change your wording. Give a complete code example. – Basil Bourque Dec 17 '20 at 18:31
  • FYI: [*How do I get an IntStream from a List?*](https://stackoverflow.com/q/24633913/642706) – Basil Bourque Dec 17 '20 at 18:39

1 Answers1

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);
        }
    }
}
David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32