Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,20 @@

import java.util.List;

import org.springframework.util.Assert;

/**
* Utility methods to obtain sublists.
*
* @author Mark Paluch
* @author qkrtkdwns3410
*/
class CollectionUtils {

private CollectionUtils() {
// prevent instantiation
}

/**
* Return the first {@code count} items from the list.
*
Expand All @@ -33,6 +40,7 @@ class CollectionUtils {
* @param <T> the element type of the lists.
*/
public static <T> List<T> getFirst(int count, List<T> list) {
Assert.notNull(list, "List must not be null");

if (count > 0 && list.size() > count) {
return list.subList(0, count);
Expand All @@ -50,9 +58,10 @@ public static <T> List<T> getFirst(int count, List<T> list) {
* @param <T> the element type of the lists.
*/
public static <T> List<T> getLast(int count, List<T> list) {
Assert.notNull(list, "List must not be null");

if (count > 0 && list.size() > count) {
return list.subList(list.size() - (count), list.size());
return list.subList(list.size() - count, list.size());
}

return list;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
* Unit tests for {@link CollectionUtils}.
*
* @author Mark Paluch
* @author qkrtkdwns3410
*/
class CollectionUtilsUnitTests {

Expand All @@ -43,4 +44,14 @@ void shouldReturnLastItems() {
assertThat(CollectionUtils.getLast(2, List.of(1, 2))).containsExactly(1, 2);
assertThat(CollectionUtils.getLast(2, List.of(1))).containsExactly(1);
}

@Test // GH-4108
void getFirstShouldRejectNullList() {
assertThatIllegalArgumentException().isThrownBy(() -> CollectionUtils.getFirst(2, null));
}

@Test // GH-4108
void getLastShouldRejectNullList() {
assertThatIllegalArgumentException().isThrownBy(() -> CollectionUtils.getLast(2, null));
}
}