I know that limit
method can limit the Java Stream
length by specified value.
But is there a way to limit the Stream
length by the total of int values that are field of items of the stream?
The stream is made from List
.
The requirements are:
- The way needs to be able to execute processes in parallel
- The way needs to create
Stream
object. - I prefer to use Java8 if possible.
Now I implement it by the following way.
- Use
for
statement and count the total. - And then
break
thefor
statement when the total reaches the limit value.
But this way cannot satisfy the requirements.
If limitByTotalIntOf
method is given, the ideal way I want is:
class Item { int value; }
List<Item> listOfItems = createListOfItems();
int limitValue = 10000;
listOfItems.parallelStream()
.map(item -> /* set value */)
.limitByTotalIntOf(limitValue, item -> item.value)
.map(item -> /* do something */);
Current way is:
int total = 0;
for(Item item: listOfItems) {
int v = /* set value */;
total += v;
if(total < limitValue) break;
/* do something */
}
Is there any way to satisfy the requirements?