简体   繁体   中英

Android java make two similar for loops into one loop

Im trying to merge these two for loops together so that i can use it for one fillview.

Ive been trying to try for a few days but am unsure how to do this so would appreciate some help!

Any help is appreciated

    int maxDataSetSize = Math.max(data1.size(), Math.max(data2.size(), data3.size())) ;

    for (int i = 0; i < maxDataSetSize; i++) {
        String dataset1Value = data1.size() > i ? data1.get(i) : null;
        String dataset2Value = data2.size() > i ? data2.get(i) : null;
        String dataset3Value = data3.size() > i ? data3.get(i) : null;

        View statsRowview = getLayoutInflater().inflate(R.layout.stats_row, null);

        fillView(statsRowview, dataset1Value, dataset2Value, dataset3Value);

        tableStats.addView(statsRowview);
    }


    int maxDataSetSize2 = Math.max(data4.size(), Math.max(data5.size(), data6.size()));
    for (int i = 0; i < maxDataSetSize2; i++) {
        String dataset4Value = data4.size() > i ? data4.get(i) : DEFAULT_COLOR;
        String dataset5Value = data5.size() > i ? data5.get(i) : DEFAULT_COLOR;
        String dataset6Value = data6.size() > i ? data6.get(i) : DEFAULT_COLOR;

        View statsRowview = getLayoutInflater().inflate(R.layout.stats_row, null);

        fillView2(statsRowview, dataset4Value, dataset5Value, dataset6Value);

        tableStats.addView(statsRowview);
    }
}

Try this:

int maxDataSetSize = Math.max(data1.size(), Math.max(data2.size(), data3.size())) ;
int maxDataSetSize2 = Math.max(data4.size(), Math.max(data5.size(), data6.size()));

for (int i = 0, j = 0; i < maxDataSetSize || j < maxDataSetSize2; i++, j++) {

    View statsRowview = getLayoutInflater().inflate(R.layout.stats_row, null);

    if(i < maxDataSetSize){
        String dataset1Value = data1.size() > i ? data1.get(i) : null;
        String dataset2Value = data2.size() > i ? data2.get(i) : null;
        String dataset3Value = data3.size() > i ? data3.get(i) : null;
        fillView(statsRowview, dataset1Value, dataset2Value, dataset3Value);
    }


    if(j < maxDataSetSize2){
        String dataset4Value = data4.size() > j ? data4.get(j) : DEFAULT_COLOR;
        String dataset5Value = data5.size() > j ? data5.get(j) : DEFAULT_COLOR;
        String dataset6Value = data6.size() > j ? data6.get(j) : DEFAULT_COLOR;
        fillView2(statsRowview, dataset4Value, dataset5Value, dataset6Value);
    }

    tableStats.addView(statsRowview);
}

This should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM