Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 sum up to a limit with streams

I have this LinkedHashMap:

myMap = {
  0 => 10,
  1 => 6,
  2 => 28,
  ...
}
int limit = 15;

What I'd want to do using streams is to sum (in order) the map values, and stop when the limit is reached, and return back the correspective index in the map (in this case 0). Is there an elegant way with streams?

like image 227
Andrea Giuliano Avatar asked Mar 08 '26 23:03

Andrea Giuliano


1 Answers

You could sum up to a limit like this

myMap.values().reduce(0, (a, b) -> a+b > limit ? a : a + b);
like image 127
Meme Composer Avatar answered Mar 11 '26 12:03

Meme Composer