Skip to content

Instantly share code, notes, and snippets.

@jnape
Created May 6, 2012 18:14
Show Gist options
  • Save jnape/2623606 to your computer and use it in GitHub Desktop.
Save jnape/2623606 to your computer and use it in GitHub Desktop.
algorithm for creating groups from list in java
package com.jnape.dynamiccollection.operation;
import com.jnape.dynamiccollection.list.DynamicArrayList;
import com.jnape.dynamiccollection.list.DynamicList;
import java.util.List;
import static java.lang.Math.min;
public class InGroupsOf {
public static <Element> DynamicList<DynamicList<Element>> inGroupsOf(List<Element> elements, int elementsPerGroup) {
DynamicList<Element> defensiveCopy = new DynamicArrayList<Element>(elements);
DynamicList<DynamicList<Element>> groups = new DynamicArrayList<DynamicList<Element>>();
int index = -elementsPerGroup;
int numberOfElements = elements.size();
while ((index += elementsPerGroup) < numberOfElements) {
int endIndex = min((index + elementsPerGroup), numberOfElements);
groups.add(defensiveCopy.subList(index, endIndex));
}
return groups;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment