Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have seen this question asked a few times, but I do not entirely understand the solutions provided. Below is a bit of code I came up with for splitting up an arraylist into five parts. I have tested and changed the array size from 0 to 16 and it works fine.

I am sure there is a "better" way of doing this, so I would like to see what others think.

public static void main(String[] args)
{
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("A");//1
    arrayList.add("B");//2
    arrayList.add("C");//3
    arrayList.add("D");//4
    arrayList.add("E");//5
    arrayList.add("F");//6
    arrayList.add("G");//7
    arrayList.add("H");//8
    arrayList.add("I");//9
    arrayList.add("J");//10
    arrayList.add("K");//11
    arrayList.add("L");//12
    arrayList.add("M");//13
    arrayList.add("N");//14
    arrayList.add("O");//15
    arrayList.add("P");//16
    arrayList.add("X");//17

    int i1 = (int) Math.ceil(arrayList.size()/5.0);

    List<String> sublist = new ArrayList<String>();
    int x=0;
    for(int p=0; p<i1; p++)
    {
        if(arrayList.size()>=(x+5))
        {
            sublist = new ArrayList<String>(arrayList.subList(x, x+5));
            x+=5;
        }
        else
            sublist = new ArrayList<String>(arrayList.subList(x, arrayList.size()));
        for(String slist : sublist)
        {
            System.out.println("i:"+slist);
        }
    }
}
share|improve this question
add comment

migrated from stackoverflow.com Jun 28 '13 at 20:58

This question came from our site for professional and enthusiast programmers.

1 Answer

How about this:

public static void main(String[] args) {
    List<String> arrayList = new ArrayList<String>();
    for (int i = 0; i < 23; i++) {
        arrayList.add(String.valueOf(i));
    }

    for (int start = 0; start < arrayList.size(); start += 5) {
        int end = Math.min(start + 5, arrayList.size());
        List<String> sublist = arrayList.subList(start, end);
        System.out.println(sublist);
    }
}

So instead of counting the segment of the list and increasing a second counter by 5 each time, you can just increase the first counter by five in the third argument of the for loop. Also, you can use the result of subList directly, without passing it to a constructor first. And you can get rid of the if-else by using min to determine the end index.

Output:

[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
[20, 21, 22]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.