Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Executing an action after X elements of a Stream  RSS feed

 
William Antônio Siqueira
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know we have a couple of ways to solve this, but I wanted to find the most elegant one.
Let's say we have a file, and after reading X elements we want to do some specific action, and so on.

Let's say X = 3, so:
1
2
3
DoTheAction
4
5
6
DoTheAction
...

What's the best way to achieve that with Stream library? I did the following, but I'm sure it's possible to make a better implementation using Collectors or even the Stream itself...



I also tried to use peak and increment a variable to count the elements, but I can't modify local variables in a lambda expression. I also tried to use count, but it's a terminate operation...

I will appreciate any input!
 
Rob Spoor
Sheriff
Posts: 20904
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about using forEach?
This could perhaps be rewritten using a lambda expression, although that pos field makes it a bit trickier - I haven't seen lambda expressions with state before.
 
Cay Horstmann
author
Ranch Hand
Posts: 172
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first solution isn't taking full advantage of streams because it dumps the contents into a list. You want to leave it in a stream so you can parallelize.

So, to make this more interesting, let's assume that we want to parallelize the processing of each line. (The reading of the lines is obviously sequential.)

Using forEach won't parallelize. You can imagine that bad things will happen to pos when it is incremented concurrently.

Instead, you want to add a line number to each line (e.g. with map), or filter with a global counter, like you did, and then turn the stream parallel.

Cheers,

Cay
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!