If I have items like this
-> [1,2,3,4,5,6,7,8,9,10]
And if ChunkSize =3, spring batch ItemReader reads item like
[1,2,3]
[4,5,6]
[7,8,9]
[10]
But, I want to
[1,2,3]
[4,5,6]
[7,8,9,10]
Is there any way to do this?
CodePudding user response:
You can make the adjustment by checking the size of the last item in the result, and if it's smaller than the chunkSize
, then append it to the second-last item of the result:
fun main() {
val l = listOf(1,2,3,4,5,6,7,8,9,10,11)
val chunkSize = 3
val c = l.chunked(chunkSize)
println(c)
val d = if (c.size >= 2 && c.last().size < chunkSize)
c.slice(0..c.lastIndex - 2) listOf(c[c.lastIndex - 1] c.last())
else
c
println(d)
}
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
CodePudding user response:
val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val chunkSize = 3
val result = list.chunked(chunkSize)
.run {
if (isNotEmpty() && last().count() != chunkSize) {
dropLast(2) listOf(takeLast(2).flatten())
} else {
this
}
}
println(result) // Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]