Divide A List To Number of Sublist in JAVA

This is basic program in java to Divide A List To Number of Sublist in JAVA, in case we want to devide a list into many sublists based on the condition.


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListTest {

public static void main(String[] args) {
List list = new ArrayList();
Scanner scn = new Scanner(System.in);
System.out.println("Type list limit n");
int limitList = scn.nextInt();
for (int x = 1; x <= limitList; x++) {
list.add(x);
}
System.out.println("type number of new sub list from old list");
int n = scn.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
List ll = new ArrayList(filterList(list, n, i));
System.out.println(ll);
}

}

public static List filterList(List l, int newListNumber, int number) {
List newList = new ArrayList();
int newListSize = l.size() / newListNumber;
int firstIndex;
int lastIndex;
if (number == 0) {
firstIndex = 0;
} else {
firstIndex = (newListSize * number) + 1;
}
if (number == 0) {
lastIndex = (newListSize * 1);
} else {
lastIndex = (firstIndex + newListSize) - 1;
}

for (int i = 0; i < l.size(); i++) {
if (i >= firstIndex && i <= lastIndex) {
newList.add(l.get(i));
}
}
return newList;

}

}

Post a Comment

Previous Post Next Post