I have as input (STDIN)
0 0 1 2 1
and I want to create a stream from it the simplest possible way.
I did create a stream by reading one by one each integer and storing them into an ArrayList. From there I just had to use .stream().reduce() to make it work.
What I want is a possible way to create a stream directly from the input
I tried to adapt this code :
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
IntStream is2 = IntStream.generate(inputStream::read).limit(inputStream.available());
by using a DataInputStream and the readInt() method
DataInputStream dis = new DataInputStream(System.in);
IntStream is2 = IntStream.generate(dis::readInt).limit(5);//later : dis.available() instead of 5
but it doesn't work I've incompatible thrown types IOException on the generate function.
Can I do it ? Or is there another way to transform an input into a stream
my reduce function to be applied is
reduce( (x , y) -> x ^ y)
I've already done this on ArrayList quite easily by doing
list.stream().reduce( (x , y) -> x ^ y);
SOLUTION
I've tried using this with a scanner to do the job but unsuccessfully and now I managed to make it work
Scanner sc = new Scanner(System.in);
int oi = Stream.of(sc.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.reduce( (x , y) -> x ^ y).getAsInt();
System.out.println(oi);
I don't understand why it didn't work at the beginning
SOLUTION
Scanner sc = new Scanner(System.in);
int oi = Stream.of(sc.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.reduce( (x , y) -> x ^ y).getAsInt();
System.out.println(oi);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With