Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Integer Stream Vs IntStream

With the following code I am getting below compilation error. I also tried using input as List of Integer instead of int[] and with that it is working fine. It is also working fine if I use boxed().

My question really is does it has to be Integer stream instead if Int Stream and whats the deal with the error message "bad return type in lambda expression int[] cannot be converted to int"

public static void main(String[] args) {
    int[] numbers = {1,2,3,4};

    List<int[]> result1 = Arrays.stream(numbers).flatMap(chara -> Arrays.stream(numbers)
            .map(operand -> new int[]{1, 2})).collect(Collectors.toList());
}

Error:(13, 49) java: incompatible types: bad return type in lambda expression int[] cannot be converted to int Error:(13, 66) java: method collect in interface java.util.stream.IntStream cannot be applied to given types; required: java.util.function.Supplier,java.util.function.ObjIntConsumer,java.util.function.BiConsumer found: java.util.stream.Collector> reason: cannot infer type-variable(s) R (actual and formal argument lists differ in length)

like image 978
Anuj Jain Avatar asked Jul 24 '18 18:07

Anuj Jain


1 Answers

I also tried using input as List of Integer instead of int[] and with that it is working fine. It is also working fine if I use boxed()

So, that essentially means you've tried:

List<int[]> result1 = numbers.stream() 
                             .flatMap(chara -> numbers.stream()
                             .map(operand -> new int[]{1, 2}))
                             .collect(Collectors.toList());

given numbers is a List<Integer>.

and:

List<int[]> result1 = Arrays.stream(numbers)
                            .boxed()
                            .flatMap(chara -> Arrays.stream(numbers).boxed()
                            .map(operand -> new int[]{1, 2}))
                            .collect(Collectors.toList());

given numbers is a int[].

Yes, this does compile but this is not readable at all and there is definitely a better approach to generate the same result (shown later in the post).

As for the compilation errors, that's because of Arrays.stream(numbers) generates an IntStream and you're trying to map to a reference type (int[]) instead of primitive int which the function to IntStream#map expects. even if you were to solve that problem by doing Arrays.stream(numbers).boxed().. there would still be another problem down the line.

What your code pretty much does is this:

Stream.generate(() -> new int[]{1, 2})
      .limit(numbers.length * numbers.length)
      .collect(Collectors.toList());

or:

IntStream.rangeClosed(1, numbers.length * numbers.length)
         .mapToObj(n -> new int[]{1, 2})
         .collect(Collectors.toList());

but in a more idiomatic, readable and efficient way.

like image 88
Ousmane D. Avatar answered Oct 02 '22 18:10

Ousmane D.