More generic way that can handle longer inner lists.
@Test
fun `Test groupByIndexed`() {
val mapOfLists = arrayListOf(
arrayListOf("a", "1"),
arrayListOf("b", "2"),
arrayListOf("c", "3")
)
.asSequence()
.flatMap { it.asSequence() }
.groupByIndexed { idx, _ ->
idx % 2 // Use how many elements have each inner list
}
// Convert Map<List<String>> to desired ArrayList<ArrayList<String>>
val arrayListOfArrayLists = ArrayList<ArrayList<String>>()
mapOfLists
.asSequence()
.map {
ArrayList<String>().apply {
addAll(it.component2())
}
}
.toCollection(arrayListOfArrayLists)
Assertions.assertEquals(2, arrayListOfArrayLists.size)
Assertions.assertEquals(arrayListOf("a", "b", "c"), arrayListOfArrayLists[0])
Assertions.assertEquals(arrayListOf("1", "2", "3"), arrayListOfArrayLists[1])
}
private fun <T, K> Sequence<T>.groupByIndexed(keySelector: (Int, T) -> K): Map<K, List<T>> {
val data = LinkedHashMap<K, MutableList<T>>()
return foldIndexed(data) { idx, acc, str ->
val key = keySelector(idx, str)
val list = acc.getOrPut(key) { mutableListOf() }
list.add(str)
acc
}
}
List<List<String>>.)