1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
import java.util.ArrayList;
import java.util.List;
public class Partition {
// Generic function to partition a list into sublists of size n each in Java
// (The final list might have less items)
public static<T> List[] Partition(List<T> list, int n)
{
// get size of the list
int size = list.size();
// calculate number of partitions m of size n each
int m = size / n;
if (size % n != 0)
m++;
// create m empty lists
List<T>[] partition = new ArrayList[m];
for (int i = 0; i < m; i++)
partition[i] = new ArrayList();
// process each element of the list and add it corresponding
// list based on its position in the original list
for (int i = 0; i < size; i++)
{
int index = i / n;
partition[index].add(list.get(i));
}
// return the lists
return partition;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestPartition {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(33);
myList.add(15);
myList.add(20);
myList.add(34);
myList.add(8);
myList.add(12);
Partition pt = new Partition();
pt.Partition(myList, 2);
}
} |