Created
May 6, 2012 18:14
-
-
Save jnape/2623606 to your computer and use it in GitHub Desktop.
algorithm for creating groups from list in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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