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;
}
recordList
should have records objects : [100,10], [500,20], [302,5] records
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With