Reputation:
I was using this macro in cpp
forn(i,3) cin>>arr[n]; //assume arr initialised earlier
So I was tried to achieve this in Java using lambda and IntStream
Scanner sc = new Scanner(System.in);
IntStream.range(0, 5).map(i->arr[i]).forEach(e->e=sc.nextInt());
But I know that stream doesn't manipulate the underlying data structure. so Can I achieve this using streams or I've to create my own functional interface to do so? thank you
Upvotes: 2
Views: 1046
Reputation: 31968
You seem to be looking for the use of toArray
with IntStream
while you map the integer provided as an input:
int arr[] = IntStream.range(0, 5).map(i -> sc.nextInt()).toArray()
Upvotes: 3
Reputation: 3559
Just change your code to
Scanner sc = new Scanner(System.in);
IntStream.range(0, 5).forEach(i -> arr[i] = sc.nextInt());
But also note that this is not a great use case for Streams. A simple loop would probably be more appropriate.
Upvotes: 3