Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to divide a list into lists of n size

I have an ArrayList, which I want to divide into smaller List objects of n size, and perform an operation on each. My current method of doing this is implemented with ArrayList objects in Java. Any pseudocode will do.

    for (int i = 1; i <= Math.floor((A.size() / n)); i++) {             ArrayList temp = subArray(A, ((i * n) - n),                     (i * n) - 1);             // do stuff with temp         }      private ArrayList<Comparable> subArray(ArrayList A, int start,                 int end) {             ArrayList toReturn = new ArrayList();             for (int i = start; i <= end; i++) {                 toReturn.add(A.get(i));             }             return toReturn;         } 

where A is the list and n is the size of the desired lists

I believe this way is taking too much time when working with considerably large lists of up to 1 million in size, so I'm trying to figure out what would be more efficient.

like image 230
Rowhawn Avatar asked Apr 28 '11 20:04

Rowhawn


People also ask

What does Listutils partition do?

Returns a List containing all the elements in collection that are also in retain . Selects all elements from input collection which match the given predicate into an output list.

What is list of () in Java?

The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.

What is partitioning in Java?

java. In number theory, * a partition of N is a way to write it as a sum of positive integers. * Two sums that differ only in the order of their terms are considered * the same partition.


1 Answers

You'll want to do something that makes use of List.subList(int, int) views rather than copying each sublist. To do this really easily, use Guava's Lists.partition(List, int) method:

List<Foo> foos = ... for (List<Foo> partition : Lists.partition(foos, n)) {   // do something with partition } 

Note that this, like many things, isn't very efficient with a List that isn't RandomAccess (such as a LinkedList).

like image 85
ColinD Avatar answered Sep 23 '22 10:09

ColinD