Java Stream collect data from map based on value

Viewed 132

I have a Map<long, integer> and I want to convert it to collection of list but condition is single list can contain indexes with sum of their value less than X . How to achieved this through java streams? Code that need to be changed to using streams is

int count=0;
   List<Long> values =new LinkedList<>();
    Collection<List<Long>> collection =new LinkedList<>();
   for(Map.Entry<Long,Integer> entry : maptoProcess.entrySet())
   {
       if(count+entry.getValue()<=maxNumberAllowed){
           values.add(entry.getKey());
           count+=entry.getValue();
       }
       else
       {   collection.add(values);
             count=0;
           values=new linkedList();
       }
   }
  

Ex :- Map{{1,300},{2,50},{3,100}} maxNumberAllowed :- 300 output :- list [[1],[2,3]]

0 Answers
Related