在列表上动态迭代

时间:2014-01-27 17:25:25

标签: java arrays list collections

我有一个如下所示的方法:

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.在这种情况下,minmax将具有相同的值。

我提出了以下方法:

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;
    }
}

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

您的代码看起来非常合理且易于理解。我认为没有迫切需要改变。