In this post, we will explore one easy way to spill a big list into few smaller sublists. Though we have many third-party libraries that help us accomplish this very same task, many times we can't go for those third-party libraries due to the constraint of our product security in that case we end up writing our own logic to split that huge list into smaller sub-lists. And this is also a very common interview question that aspirants come across. though we will be using java to implement this logic I think the language here is not a barrier for those who wish to implement this same logic in java scripts or C# or objective C. So my request to them is to please go through the logic it is a simple and elegant way to split a big list.
So, here is the java code to split a big list into a smaller sublist of fixed size -
public List<List<String>> partitionList(List<String> list, int partitionNumber) {
int listSize = list.size();
int m = listSize / partitionNumber;
if (listSize % partitionNumber != 0) {
m++;
}
List<String>[] partition = new ArrayList[m];
for (int i = 0; i < m; i++) {
partition[i] = new ArrayList();
}
for (int i = 0; i < listSize; i++) {
int index = i / partitionNumber;
partition[index].add(list.get(i));
}
return Arrays.asList(partition);
}
Comments
Post a Comment