我有一个如下所示的方法:
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;
}
}
有更好的方法吗?
答案 0 :(得分:0)
您的代码看起来非常合理且易于理解。我认为没有迫切需要改变。