0

Array /Stream API problem

I'm trying to print the numbers of an array to the second power in one row separated by single whitespaces using stream API like this: int[] arr = {5, 3, 1}; Arrays.stream(arr) .map(x -> (int)Math.pow(x, 2)) .map(x -> x + " ") .forEach(System.out::print); In this row --> .map(x -> x + " ") i get an exception ( Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from String to int ) The strange thing if I try the same this using this method but on an ArrayList it is working fine: List<Integer> nums = new ArrayList<Integer>(); nums.add(3); nums.add(2); nums.stream() .map(x -> (int)Math.pow(x, 2)) .map(x -> x + " ") .forEach(System.out::print); If anyone could help me I would really appreciate it :)

13th Feb 2021, 8:38 AM
Bäck András
Bäck András - avatar
2 Respuestas
+ 1
Try mapToObj instead, it will an returns an object-valued stream. This works fine: int[] arr = {5, 3, 1}; Arrays.stream(arr) .map(x -> (int)Math.pow(x, 2)) .mapToObj(x -> x + " ") .forEach(System.out::print); I think this code runs because Integer is a wrapper not primitive type. List<Integer> nums = new ArrayList<Integer>(); nums.add(3); nums.add(2); nums.stream() .map(x -> (int)Math.pow(x, 2)) .map(x -> x + " ") .forEach(System.out::print);
13th Feb 2021, 9:03 AM
0_O-[Mägár_Sám_Äkà_Nüllpøïntêr_Èxëcéptïön]~~
0_O-[Mägár_Sám_Äkà_Nüllpøïntêr_Èxëcéptïön]~~ - avatar
+ 1
0_O-[Mägár_Sám_Äkà_Nüllpøïntêr_Èxëcéptïön]~~ Thanks, you solution works :) I also checked your explanation, and it seems to be true, this code is also running fine: Integer[] array = {3, 2, 5}; Arrays.stream(array) .map(x -> (int)Math.pow(x, 2)) .map(x -> x + " ") .forEach(System.out::print);
13th Feb 2021, 9:25 AM
Bäck András
Bäck András - avatar