Reputation: 4075
In the official documentation of the Kotlin language there is a function zipWithNextthat is presented as follows.
val letters = listOf("a", "b", "c", "d", "e", "f")
val pairs = letters.zipWithNext {a, b -> a + b} // [ab, bc, cd, de, ef]
Is there a way to summarize only part of the elements of this list, and leave the rest unchanged?
For comparison, you can use another listOf("bc", "de")
.
In this case the final output should looks like [a, bc, de, f]
Upvotes: 1
Views: 2425
Reputation: 164139
I assume that the initial list's size is an even number, otherwise you cannot get your expected result.
For
val letters = listOf("a", "b", "c", "d", "e", "f")
with zipWithNext()
:
val pairs = (listOf("") + letters + listOf(""))
.zipWithNext()
.filterIndexed { index, _ -> index % 2 == 0 }
.map { it.first + it.second }
with chunked(2)
:
val pairs = listOf(letters.first()) +
letters.subList(1, letters.size - 1).chunked(2).map { it[0] + it[1] } +
listOf(letters.last())
both give this result:
[a, bc, de, f]
Edit
As for the comparison list:
fun getNewList(list: List<String>, comparison: List<String>) : List<String> {
val newList = mutableListOf<String>()
var flag = false
list.forEachIndexed { i, s ->
if (i < list.size - 1) {
if (!flag) {
val item = s + list[i + 1]
if (comparison.contains(item)) {
newList.add(item)
flag = true
} else {
newList.add(s)
}
} else {
flag = false
}
} else {
newList.add(s)
}
}
return newList
}
this code:
val letters = listOf("a", "b", "c", "d", "e", "f")
val comparison = listOf("bc", "de")
val newList = getNewList(letters, comparison)
println(newList)
will print:
[a, bc, de, f]
Upvotes: 2