Imr*_*han 5 java java-8 java-stream
如何获取记录,计数总和应该在限制内。在下面的示例中,Records对象包含 recordId 和计数,我想根据计数的总和应该小于或等于我的限制条件来获取记录数据。
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;
}
Run Code Online (Sandbox Code Playgroud)
recordList 应该有记录对象:[100,10], [500,20], [302,5] 记录
使用 Stream API 解决此问题的问题是,您必须将一些信息保留在处理上下文之外,并同时读取/更新(依赖)它。这些任务不适合 Stream API。
使用 for 循环来代替,它非常适合并且非常适合于此:
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);
Run Code Online (Sandbox Code Playgroud)