Skip to content

Instantly share code, notes, and snippets.

@seijikohara
Forked from tksmaru/CollectionUtils.java
Last active May 28, 2017 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seijikohara/ab25c8e973a2afb286ec16d89891ab37 to your computer and use it in GitHub Desktop.
Save seijikohara/ab25c8e973a2afb286ec16d89891ab37 to your computer and use it in GitHub Desktop.
Listを指定サイズ毎に分割するutility
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CollectionUtils {
/**
* Listを指定したサイズ毎に分割します。
*
* @param origin 分割元のList
* @param size Listの分割単位
* @return サイズ毎に分割されたList。但し、Listがnullまたは空の場合、もしくはsizeが0以下の場合は空のListを返す。
*/
public static <T> List<List<T>> divide(List<T> origin, int size) {
if (origin == null || origin.isEmpty() || size <= 0) {
return Collections.emptyList();
}
int block = origin.size() / size + (origin.size() % size > 0 ? 1 : 0);
return IntStream.range(0, block)
.boxed()
.map(i -> {
int start = i * size;
int end = Math.min(start + size, origin.size());
return origin.subList(start, end);
})
.collect(Collectors.toList());
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(JUnit4.class)
public class CollectionUtilsTest {
@Test
public void testDivide() {
assertThat(
CollectionUtils.divide(null, 3),
is(emptyList()));
assertThat(
CollectionUtils.divide(emptyList(), 3),
is(emptyList()));
assertThat(
CollectionUtils.divide(
asList(1, 2, 3),
0
),
is(emptyList()));
assertThat(
CollectionUtils.divide(
asList(1),
1
),
is(asList(
asList(1)
)));
assertThat(
CollectionUtils.divide(
asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
3
),
is(asList(
asList(1, 2, 3),
asList(4, 5, 6),
asList(7, 8, 9),
asList(10)
)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment