I have an ArrayList of 750 elements I would like to divide that ArrayList into 150 subarraylists so 5 elements to each subarraylist.

I have this code but it not working

while (scanner.hasNextLine()) {
            String t = scanner.nextLine();
            String[] ar = t.split(",");

            for (int i = 0; i < ar.length; i++) 
            {
                add.add(Double.parseDouble(ar[i]));
            }

Recommended Answers

Your sample code doesn't say what "add" is, but I'll guess it's the full sized ArrayList with 150 elements.

Do you really need to create 30 more ArrayLists to hold them in groups of 5? You can get a view of 5 consecutive elements from that list, starting at any …

Jump to Post

All 3 Replies

Your sample code doesn't say what "add" is, but I'll guess it's the full sized ArrayList with 150 elements.

Do you really need to create 30 more ArrayLists to hold them in groups of 5? You can get a view of 5 consecutive elements from that list, starting at any given index with:

    List<Double> five = add.subList(i, Math.min(i+5, add.size());

The syntax is similar to .substring() on a String object. Calling .sublist(i,j) returns all element from index i (inclusive) to index j (exclusive). If you need that to specifically be an ArrayList, you can pass that to ArrayList's Constructor:

    ArrayList<Double> five = new ArrayList<>(add.subList(i, Math.min(i+5, add.size())));

The business with Math.min() simply insures that j is never more than the size of the original list. You can leave that out and just write .sublist(i,i+5) if both i and the length of the large list are always multiples of 5.

PS. Please mark threads solved so others know. +1 to Husoki.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.