[英]iterating over dynamically arrray list which internally contain two indexes
[英]iterating dynamically over the list
我有一個如下所示的方法:
List<AbcObject> aaList= session.createCriteria(AbcObject.class)
aaList
包含以下元素:
t_id value
11 3
12 20
14 60
15 27 ------->(3+20+60+27=100), here min=11 & max=15
18 40
22 20
33 40
45 20 -------->(40+20+40+20=100), here min=18 & max=45
我必須對列表進行迭代,以便如果value
的運行總和達到100,則將一個元素添加到另一個列表中,如下所示:
min max
11 15
18 45
請注意,完成除法運算的100
值必須是可配置的。
也有可能第一個元素本身的值為100。在這種情況下, min
和max
的值相同。
我想出了以下方法:
final int BARRIER = 100;
//I am going to assume there are getter methods in your AbcObject and
//that all values are greater than 0
List<int[]> minMaxs = new List<int[]>();
int sum = 0;
int min = 0;
for (AbcObject obj: aaList) {
if (sum == 0) {
//start over, remember min
min = obj.getT_id();
}
//add value to sum
sum += obj.getValue();
if (sum >= BARRIER) {
//now we need to start again, remember what we got
minMaxs.add(new int[]{min, obj.getT_id()});
//reset
min = 0;
sum = 0;
}
}
我發現的另一種方法是:
final int BARRIER = 100;
//I am going to assume there are getter methods in your AbcObject and
//that all values are greater than 0
List<AbcObject> minMaxs = new List<AbcObject>();
int sum = 0;
int min = 0;
for (AbcObject obj: aaList) {
if (sum == 0) {
//start over, remember min
min = obj.getT_id();
}
//add value to sum
sum += obj.getValue();
if (sum >= BARRIER) {
//now we need to start again, remember what we got
minMaxs.add(new AbcObject(min, obj.getT_id()));
//reset
min = 0;
sum = 0;
}
}
有沒有更好的方法?
您的代碼看起來非常合理,而且易於理解。 我認為沒有迫切需要進行更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.