Introducing windowed() and chunked()
package com.baeldung.collections
+import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
@@ -143,4 +144,69 @@ class CollectionsTest {
print(finalResult)
assertEquals(1091, finalResult)
}
+
+ @Test
+ fun whenApplyingChunked_thenShouldBreakTheCollection() {
+ val theList = listOf(1, 2, 3, 4, 5)
+ val chunked = theList.chunked(2)
+
+ assertThat(chunked.size).isEqualTo(3)
+ assertThat(chunked.first()).contains(1, 2)
+ assertThat(chunked[1]).contains(3, 4)
+ assertThat(chunked.last()).contains(5)
+ }
+
+ @Test
+ fun whenApplyingChunkedWithTransformation_thenShouldBreakTheCollection() {
+ val theList = listOf(1, 2, 3, 4, 5)
+ val chunked = theList.chunked(3) { it.joinToString(", ") }
+
+ assertThat(chunked.size).isEqualTo(2)
+ assertThat(chunked.first()).isEqualTo("1, 2, 3")
+ assertThat(chunked.last()).isEqualTo("4, 5")
+ }
+
+ @Test
+ fun whenApplyingWindowed_thenShouldCreateSlidingWindowsOfElements() {
+ val theList = (1..6).toList()
+ val windowed = theList.windowed(3)
+
+ assertThat(windowed.size).isEqualTo(4)
+ assertThat(windowed.first()).contains(1, 2, 3)
+ assertThat(windowed[1]).contains(2, 3, 4)
+ assertThat(windowed[2]).contains(3, 4, 5)
+ assertThat(windowed.last()).contains(4, 5, 6)
+ }
+
+ @Test
+ fun whenApplyingWindowedWithTwoSteps_thenShouldCreateSlidingWindowsOfElements() {
+ val theList = (1..6).toList()
+ val windowed = theList.windowed(size = 3, step = 2)
+
+ assertThat(windowed.size).isEqualTo(2)
+ assertThat(windowed.first()).contains(1, 2, 3)
+ assertThat(windowed.last()).contains(3, 4, 5)
+ }
+
+ @Test
+ fun whenApplyingPartialWindowedWithTwoSteps_thenShouldCreateSlidingWindowsOfElements() {
+ val theList = (1..6).toList()
+ val windowed = theList.windowed(size = 3, step = 2, partialWindows = true)
+
+ assertThat(windowed.size).isEqualTo(3)
+ assertThat(windowed.first()).contains(1, 2, 3)
+ assertThat(windowed[1]).contains(3, 4, 5)
+ assertThat(windowed.last()).contains(5, 6)
+ }
+
+ @Test
+ fun whenApplyingTransformingWindows_thenShouldCreateSlidingWindowsOfElements() {
+ val theList = (1..6).toList()
+ val windowed = theList.windowed(size = 3, step = 2, partialWindows = true) { it.joinToString(", ") }
+
+ assertThat(windowed.size).isEqualTo(3)
+ assertThat(windowed.first()).isEqualTo("1, 2, 3")
+ assertThat(windowed[1]).isEqualTo("3, 4, 5")
+ assertThat(windowed.last()).isEqualTo("5, 6")
+ }
}
