Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'cannot find symbol error' when attempting to use .stream() on array in Java [duplicate]

I am attempting to implement the Java.stream() method to multiple a list of numbers together in Java 8. I have imported the java.util.stream*; package. The static method is set to return an int and take in an array. However, when I call .stream().reduce() on the array, I get the error:

error: cannot find symbol
    int count = x.stream().reduce(1, (a, b) -> a * b).sum();
                 ^
  symbol:   method stream()
  location: variable x of type int[]

How can I properly use the stream() method to multiple the values of the array together in order?

The class I have defined as:

import java.util.stream.*;
public class Kata{
  public static int grow(int[] x){
    int count = x.stream().reduce(1, (a, b) -> a * b).sum();
    return count;  
  }

}
like image 285
Dog Avatar asked Jul 30 '26 00:07

Dog


2 Answers

You need Arrays.stream to convert an array into a stream:

int count = Arrays.stream(x).reduce(1, (a, b) -> a * b);

The sum() step you were doing at the end doesn't make sense, because after reduce we are already left with just a single primitive integer. So I removed it.

like image 188
Tim Biegeleisen Avatar answered Jul 31 '26 15:07

Tim Biegeleisen


First convert array into List to stream it, or you can also use Arrays.stream(x) as @Tim Biegeleisen suggestion

Arrays.asList(x).stream(x).reduce(1, (a, b) -> a * b);
like image 36
Deadpool Avatar answered Jul 31 '26 15:07

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!