Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum up List to a limit with streams

How to get the records, which count sum should be in limit. In below example there is Records Object contains recordId and count, i wanted to fetch the records data based on the total sum of count should be less than or equal to my limit condition.

public class Records {
    private int recordID;
    private int count;

    public Records(int recordID, int count) {
        this.recordID = recordID;
        this.count = count;
    }

    public int getRecordID() {
        return recordID;
    }

    public void setRecordID(int recordID) {
        this.recordID = recordID;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}


public static void main(String[] args) {
    
    final List<Records> recordList = new ArrayList<>();
    
    recordList.add(new Records(100, 10));
    recordList.add(new Records(501, 20));
    recordList.add(new Records(302, 5));
    recordList.add(new Records(405, 2));
    recordList.add(new Records(918, 8));
    int limit = 35;
}

Expected Result

recordList should have records objects : [100,10], [500,20], [302,5] records

like image 959
Imran khan Avatar asked Nov 07 '22 04:11

Imran khan


1 Answers

The problems of solving this with Stream API is that you have to keep some information outside of the context of processing and read/update (depend) on it at the same time. These tasks are not suitable for Stream API.

Use a for-loop instead which is suitable and great for this:

int index = 0;                              // highest index possible
int sum = 0;                                // sum as a temporary variable
for (int i=0; i<recordList.size(); i++) {   // for each Record
    sum += recordList.get(i).getCount();    // ... add the 'count' to the 'sum'
    if (sum <= limit) {                     // ... until the sum is below the limit
        index = i;                          // ... move the pivot
    } else break;                           // ... or else stop processing
}

// here you need to get the list from 0 to index+1 
// as long as the 2nd parameter of subList(int, int) is exlcusive
List<Record> filteredRecords = recordList.subList(0, index + 1);
like image 130
Nikolas Charalambidis Avatar answered Nov 12 '22 17:11

Nikolas Charalambidis