How to combine two different length lists in kotlin?How can I concatenate two arrays in Java?How do I join two lists in Java?What is the simplest and most robust way to get the user's current location on Android?How to compare two Arraylists which contain objects of the same class in Java?Populate List with two different objects dynamicallyhow can find positon in list String?How to convert List to Map in Kotlin?How to constantly find the two smallest values from two different lists?how to send two different sizes of lists into excel using javaHandling lists of two different types with same code using functional programming in kotlin
What is the white pattern on trim wheel for?
Convex hull in a discrete space
Why is a road bike faster than a city bike with the same effort? How much faster it can be?
Clear text passwords in Unix
How should I answer custom and border protection questions if I'm a returning citizen that hasn't been in the country for almost a decade?
What happens to a net with the Returning Weapon artificer infusion after it hits?
Youtube not blocked by iptables
Medic abilities
Is there a concept of "peer review" in Rabbinical Judaism?
Practicality of 30 year fixed mortgage at 55 years of age
Intheritance at package visibility in Java
Windows 10 deletes lots of tiny files super slowly. Anything that can be done to speed it up?
How to stop the death waves in my city?
Is the iPhone's eSim for the home or roaming carrier?
How to deal with a PC being played as homophobic?
Diminutive -ula
My manager quit. Should I agree to defer wage increase to accommodate budget concerns?
Align all symbols in a LaTeX equation
Subverting the emotional woman and stoic man trope
Garage door sticks on a bolt
Need Improvement on Script Which Continuously Tests Website
Do interval ratios take overtones into account or solely the fundamental frequency?
How can I tell the difference between fishing for rolls and being involved?
Can someone give the intuition behind Mean Absolute Error and the Median?
How to combine two different length lists in kotlin?
How can I concatenate two arrays in Java?How do I join two lists in Java?What is the simplest and most robust way to get the user's current location on Android?How to compare two Arraylists which contain objects of the same class in Java?Populate List with two different objects dynamicallyhow can find positon in list String?How to convert List to Map in Kotlin?How to constantly find the two smallest values from two different lists?how to send two different sizes of lists into excel using javaHandling lists of two different types with same code using functional programming in kotlin
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I want to combine two different length lists. For example;
val list1 = listOf(1,2,3,4,5)
val list2 = listOf("a","b","c")
I want to result like this
(1,"a",2,"b",3,"c",4,5)
Is there any suggestion?
java android kotlin kotlin-android-extensions
add a comment
|
I want to combine two different length lists. For example;
val list1 = listOf(1,2,3,4,5)
val list2 = listOf("a","b","c")
I want to result like this
(1,"a",2,"b",3,"c",4,5)
Is there any suggestion?
java android kotlin kotlin-android-extensions
Join both list as objetc and then use a comparator kotlinlang.org/api/latest/jvm/stdlib/kotlin/-comparator/…
– cutiko
Mar 28 at 18:23
Can you give an example?
– Bahadır Bulduk
Mar 28 at 18:27
add a comment
|
I want to combine two different length lists. For example;
val list1 = listOf(1,2,3,4,5)
val list2 = listOf("a","b","c")
I want to result like this
(1,"a",2,"b",3,"c",4,5)
Is there any suggestion?
java android kotlin kotlin-android-extensions
I want to combine two different length lists. For example;
val list1 = listOf(1,2,3,4,5)
val list2 = listOf("a","b","c")
I want to result like this
(1,"a",2,"b",3,"c",4,5)
Is there any suggestion?
java android kotlin kotlin-android-extensions
java android kotlin kotlin-android-extensions
asked Mar 28 at 18:19
Bahadır BuldukBahadır Bulduk
283 bronze badges
283 bronze badges
Join both list as objetc and then use a comparator kotlinlang.org/api/latest/jvm/stdlib/kotlin/-comparator/…
– cutiko
Mar 28 at 18:23
Can you give an example?
– Bahadır Bulduk
Mar 28 at 18:27
add a comment
|
Join both list as objetc and then use a comparator kotlinlang.org/api/latest/jvm/stdlib/kotlin/-comparator/…
– cutiko
Mar 28 at 18:23
Can you give an example?
– Bahadır Bulduk
Mar 28 at 18:27
Join both list as objetc and then use a comparator kotlinlang.org/api/latest/jvm/stdlib/kotlin/-comparator/…
– cutiko
Mar 28 at 18:23
Join both list as objetc and then use a comparator kotlinlang.org/api/latest/jvm/stdlib/kotlin/-comparator/…
– cutiko
Mar 28 at 18:23
Can you give an example?
– Bahadır Bulduk
Mar 28 at 18:27
Can you give an example?
– Bahadır Bulduk
Mar 28 at 18:27
add a comment
|
5 Answers
5
active
oldest
votes
You may use the .zip
function for that
list1.zip(list2) a,b -> listOf(a,b).flatten()
The only problem is that it will only process elements, with both sets, so if (like in the example) let's have different size - it will not work
The alternative could be to add specific markers and filter them or to just use iterators for that. I found an elegant solution with sequence..
function
val result = sequence
val first = list1.iterator()
val second = list2.iterator()
while (first.hasNext() && second.hasNext())
yield(first.next())
yield(second.next())
yieldAll(first)
yieldAll(second)
.toList()
My lists has different size so it doesn't work for my situation
– Bahadır Bulduk
Mar 28 at 18:29
I've updated the reply to indicate it
– Eugene Petrenko
Mar 28 at 18:31
Thank you Eugene Petrenko this is works!
– Bahadır Bulduk
Mar 29 at 4:00
add a comment
|
You could do it like this:
val mergedList = with(setOf(list1, list2).sortedByDescending it.count() )
first().mapIndexed index, e ->
listOfNotNull(e, last().getOrNull(index))
.flatten()
First, you put both lists in a Set
, then you sort it (descending) by the number of elements yielding a list of lists.
The first list has the most elements will be used for iteration.
Using mapIndexed
you can use the index
to access the corresponding element in the second list. If there is none, null
is returned and it will be filtered out by listOfNotNull
. In the end you flatten the resulting list of lists and you get the desired result:
[1, a, 2, b, 3, c, 4, 5]
add a comment
|
- If the elements from the source lists can occur in any order in the resulting list, then
>>> list1 + list2
res12: kotlin.collections.List<kotlin.Any> = [1, 2, 3, 4, 5, a, b, c]
- If the elements from the source lists should alternate in the resulting list and list1 is longer than list2, then
>>> list1.zip(list2).flatMap listOf(it.first, it.second) + list1.drop(list2.size)
res16: kotlin.collections.List<kotlin.Any> = [1, a, 2, b, 3, c, 4, 5]
nice one, but it requires you to know which will be the bigger list, in order to append the correct list (from which you dropped)
– Willi Mentzel
Mar 28 at 21:29
True and a generic solution can be created by changing the second addend toif (list1.size > list2.size) list1.drop(list2.size) else list2.drop(list1.size)
.
– Venkatesh-Prasad Ranganath
Mar 28 at 22:09
add a comment
|
Your lists are of inconvertible types (Ints and Strings) so you have to have MutableList<Any>
so that you can add both types:
val allItems = mutableListOf<Any>(1,2,3,4,5)
val list2 = listOf("a","b","c")
allItems.addAll(list2)
I can use mutableList. it ok, but addAll result is 1,2,3,4,5,6,"a","b","c" right? I want that result is 1,"a",2,"b",3,"c",4,5
– Bahadır Bulduk
Mar 28 at 18:27
You're not specifying the sort order. Do you want the items to alternate or just be sorted?
– Hamed Momeni
Mar 28 at 19:40
add a comment
|
I think Eugenes answer already contains all you need to know to combine two lists (be it zip
or combining all elements).
In case you want to combine an arbitrary number of lists, one item per alternating list, you may also be interested in the following approach:
fun combine(vararg lists: List<*>) : List<Any> = mutableListOf<Any>().also
combine(it, lists.map(List<*>::iterator))
private tailrec fun combine(targetList: MutableList<Any>, iterators: List<Iterator<*>>)
iterators.asSequence()
.filter(Iterator<*>::hasNext)
.mapNotNull(Iterator<*>::next)
.forEach targetList += it
if (iterators.asSequence().any(Iterator<*>::hasNext))
combine(targetList, iterators)
Calling it then looks as follows and leads to the value seen in the comment:
combine(list1, list2) // List containing: 1, "a", 2, "b", 3, "c", 4, 5
combine(list1, list2, listOf("hello", "world")) // 1, "a", "hello", 2, "b", "world", 3, "c", 4, 5
A simplified approach to the second part of Eugenes answer could be implemented using following code; that, of course, isn't lazy anymore as you get a list back ;-) (but maybe you even translated it directly to a list, so you can also use this approach):
fun List<Any>.combine(other: List<Any>) : List<Any> = mutableListOf<Any>().also second.hasNext())
if (first.hasNext()) it.add(first.next())
if (second.hasNext()) it.add(second.next())
Calling it would work as follows:
list1.combine(list2)
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55404428%2fhow-to-combine-two-different-length-lists-in-kotlin%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
You may use the .zip
function for that
list1.zip(list2) a,b -> listOf(a,b).flatten()
The only problem is that it will only process elements, with both sets, so if (like in the example) let's have different size - it will not work
The alternative could be to add specific markers and filter them or to just use iterators for that. I found an elegant solution with sequence..
function
val result = sequence
val first = list1.iterator()
val second = list2.iterator()
while (first.hasNext() && second.hasNext())
yield(first.next())
yield(second.next())
yieldAll(first)
yieldAll(second)
.toList()
My lists has different size so it doesn't work for my situation
– Bahadır Bulduk
Mar 28 at 18:29
I've updated the reply to indicate it
– Eugene Petrenko
Mar 28 at 18:31
Thank you Eugene Petrenko this is works!
– Bahadır Bulduk
Mar 29 at 4:00
add a comment
|
You may use the .zip
function for that
list1.zip(list2) a,b -> listOf(a,b).flatten()
The only problem is that it will only process elements, with both sets, so if (like in the example) let's have different size - it will not work
The alternative could be to add specific markers and filter them or to just use iterators for that. I found an elegant solution with sequence..
function
val result = sequence
val first = list1.iterator()
val second = list2.iterator()
while (first.hasNext() && second.hasNext())
yield(first.next())
yield(second.next())
yieldAll(first)
yieldAll(second)
.toList()
My lists has different size so it doesn't work for my situation
– Bahadır Bulduk
Mar 28 at 18:29
I've updated the reply to indicate it
– Eugene Petrenko
Mar 28 at 18:31
Thank you Eugene Petrenko this is works!
– Bahadır Bulduk
Mar 29 at 4:00
add a comment
|
You may use the .zip
function for that
list1.zip(list2) a,b -> listOf(a,b).flatten()
The only problem is that it will only process elements, with both sets, so if (like in the example) let's have different size - it will not work
The alternative could be to add specific markers and filter them or to just use iterators for that. I found an elegant solution with sequence..
function
val result = sequence
val first = list1.iterator()
val second = list2.iterator()
while (first.hasNext() && second.hasNext())
yield(first.next())
yield(second.next())
yieldAll(first)
yieldAll(second)
.toList()
You may use the .zip
function for that
list1.zip(list2) a,b -> listOf(a,b).flatten()
The only problem is that it will only process elements, with both sets, so if (like in the example) let's have different size - it will not work
The alternative could be to add specific markers and filter them or to just use iterators for that. I found an elegant solution with sequence..
function
val result = sequence
val first = list1.iterator()
val second = list2.iterator()
while (first.hasNext() && second.hasNext())
yield(first.next())
yield(second.next())
yieldAll(first)
yieldAll(second)
.toList()
edited Mar 28 at 18:31
answered Mar 28 at 18:28
Eugene PetrenkoEugene Petrenko
3,33218 silver badges27 bronze badges
3,33218 silver badges27 bronze badges
My lists has different size so it doesn't work for my situation
– Bahadır Bulduk
Mar 28 at 18:29
I've updated the reply to indicate it
– Eugene Petrenko
Mar 28 at 18:31
Thank you Eugene Petrenko this is works!
– Bahadır Bulduk
Mar 29 at 4:00
add a comment
|
My lists has different size so it doesn't work for my situation
– Bahadır Bulduk
Mar 28 at 18:29
I've updated the reply to indicate it
– Eugene Petrenko
Mar 28 at 18:31
Thank you Eugene Petrenko this is works!
– Bahadır Bulduk
Mar 29 at 4:00
My lists has different size so it doesn't work for my situation
– Bahadır Bulduk
Mar 28 at 18:29
My lists has different size so it doesn't work for my situation
– Bahadır Bulduk
Mar 28 at 18:29
I've updated the reply to indicate it
– Eugene Petrenko
Mar 28 at 18:31
I've updated the reply to indicate it
– Eugene Petrenko
Mar 28 at 18:31
Thank you Eugene Petrenko this is works!
– Bahadır Bulduk
Mar 29 at 4:00
Thank you Eugene Petrenko this is works!
– Bahadır Bulduk
Mar 29 at 4:00
add a comment
|
You could do it like this:
val mergedList = with(setOf(list1, list2).sortedByDescending it.count() )
first().mapIndexed index, e ->
listOfNotNull(e, last().getOrNull(index))
.flatten()
First, you put both lists in a Set
, then you sort it (descending) by the number of elements yielding a list of lists.
The first list has the most elements will be used for iteration.
Using mapIndexed
you can use the index
to access the corresponding element in the second list. If there is none, null
is returned and it will be filtered out by listOfNotNull
. In the end you flatten the resulting list of lists and you get the desired result:
[1, a, 2, b, 3, c, 4, 5]
add a comment
|
You could do it like this:
val mergedList = with(setOf(list1, list2).sortedByDescending it.count() )
first().mapIndexed index, e ->
listOfNotNull(e, last().getOrNull(index))
.flatten()
First, you put both lists in a Set
, then you sort it (descending) by the number of elements yielding a list of lists.
The first list has the most elements will be used for iteration.
Using mapIndexed
you can use the index
to access the corresponding element in the second list. If there is none, null
is returned and it will be filtered out by listOfNotNull
. In the end you flatten the resulting list of lists and you get the desired result:
[1, a, 2, b, 3, c, 4, 5]
add a comment
|
You could do it like this:
val mergedList = with(setOf(list1, list2).sortedByDescending it.count() )
first().mapIndexed index, e ->
listOfNotNull(e, last().getOrNull(index))
.flatten()
First, you put both lists in a Set
, then you sort it (descending) by the number of elements yielding a list of lists.
The first list has the most elements will be used for iteration.
Using mapIndexed
you can use the index
to access the corresponding element in the second list. If there is none, null
is returned and it will be filtered out by listOfNotNull
. In the end you flatten the resulting list of lists and you get the desired result:
[1, a, 2, b, 3, c, 4, 5]
You could do it like this:
val mergedList = with(setOf(list1, list2).sortedByDescending it.count() )
first().mapIndexed index, e ->
listOfNotNull(e, last().getOrNull(index))
.flatten()
First, you put both lists in a Set
, then you sort it (descending) by the number of elements yielding a list of lists.
The first list has the most elements will be used for iteration.
Using mapIndexed
you can use the index
to access the corresponding element in the second list. If there is none, null
is returned and it will be filtered out by listOfNotNull
. In the end you flatten the resulting list of lists and you get the desired result:
[1, a, 2, b, 3, c, 4, 5]
answered Mar 28 at 19:53
Willi MentzelWilli Mentzel
12.6k11 gold badges60 silver badges79 bronze badges
12.6k11 gold badges60 silver badges79 bronze badges
add a comment
|
add a comment
|
- If the elements from the source lists can occur in any order in the resulting list, then
>>> list1 + list2
res12: kotlin.collections.List<kotlin.Any> = [1, 2, 3, 4, 5, a, b, c]
- If the elements from the source lists should alternate in the resulting list and list1 is longer than list2, then
>>> list1.zip(list2).flatMap listOf(it.first, it.second) + list1.drop(list2.size)
res16: kotlin.collections.List<kotlin.Any> = [1, a, 2, b, 3, c, 4, 5]
nice one, but it requires you to know which will be the bigger list, in order to append the correct list (from which you dropped)
– Willi Mentzel
Mar 28 at 21:29
True and a generic solution can be created by changing the second addend toif (list1.size > list2.size) list1.drop(list2.size) else list2.drop(list1.size)
.
– Venkatesh-Prasad Ranganath
Mar 28 at 22:09
add a comment
|
- If the elements from the source lists can occur in any order in the resulting list, then
>>> list1 + list2
res12: kotlin.collections.List<kotlin.Any> = [1, 2, 3, 4, 5, a, b, c]
- If the elements from the source lists should alternate in the resulting list and list1 is longer than list2, then
>>> list1.zip(list2).flatMap listOf(it.first, it.second) + list1.drop(list2.size)
res16: kotlin.collections.List<kotlin.Any> = [1, a, 2, b, 3, c, 4, 5]
nice one, but it requires you to know which will be the bigger list, in order to append the correct list (from which you dropped)
– Willi Mentzel
Mar 28 at 21:29
True and a generic solution can be created by changing the second addend toif (list1.size > list2.size) list1.drop(list2.size) else list2.drop(list1.size)
.
– Venkatesh-Prasad Ranganath
Mar 28 at 22:09
add a comment
|
- If the elements from the source lists can occur in any order in the resulting list, then
>>> list1 + list2
res12: kotlin.collections.List<kotlin.Any> = [1, 2, 3, 4, 5, a, b, c]
- If the elements from the source lists should alternate in the resulting list and list1 is longer than list2, then
>>> list1.zip(list2).flatMap listOf(it.first, it.second) + list1.drop(list2.size)
res16: kotlin.collections.List<kotlin.Any> = [1, a, 2, b, 3, c, 4, 5]
- If the elements from the source lists can occur in any order in the resulting list, then
>>> list1 + list2
res12: kotlin.collections.List<kotlin.Any> = [1, 2, 3, 4, 5, a, b, c]
- If the elements from the source lists should alternate in the resulting list and list1 is longer than list2, then
>>> list1.zip(list2).flatMap listOf(it.first, it.second) + list1.drop(list2.size)
res16: kotlin.collections.List<kotlin.Any> = [1, a, 2, b, 3, c, 4, 5]
edited Mar 28 at 22:07
answered Mar 28 at 18:37
Venkatesh-Prasad RanganathVenkatesh-Prasad Ranganath
1031 silver badge10 bronze badges
1031 silver badge10 bronze badges
nice one, but it requires you to know which will be the bigger list, in order to append the correct list (from which you dropped)
– Willi Mentzel
Mar 28 at 21:29
True and a generic solution can be created by changing the second addend toif (list1.size > list2.size) list1.drop(list2.size) else list2.drop(list1.size)
.
– Venkatesh-Prasad Ranganath
Mar 28 at 22:09
add a comment
|
nice one, but it requires you to know which will be the bigger list, in order to append the correct list (from which you dropped)
– Willi Mentzel
Mar 28 at 21:29
True and a generic solution can be created by changing the second addend toif (list1.size > list2.size) list1.drop(list2.size) else list2.drop(list1.size)
.
– Venkatesh-Prasad Ranganath
Mar 28 at 22:09
nice one, but it requires you to know which will be the bigger list, in order to append the correct list (from which you dropped)
– Willi Mentzel
Mar 28 at 21:29
nice one, but it requires you to know which will be the bigger list, in order to append the correct list (from which you dropped)
– Willi Mentzel
Mar 28 at 21:29
True and a generic solution can be created by changing the second addend to
if (list1.size > list2.size) list1.drop(list2.size) else list2.drop(list1.size)
.– Venkatesh-Prasad Ranganath
Mar 28 at 22:09
True and a generic solution can be created by changing the second addend to
if (list1.size > list2.size) list1.drop(list2.size) else list2.drop(list1.size)
.– Venkatesh-Prasad Ranganath
Mar 28 at 22:09
add a comment
|
Your lists are of inconvertible types (Ints and Strings) so you have to have MutableList<Any>
so that you can add both types:
val allItems = mutableListOf<Any>(1,2,3,4,5)
val list2 = listOf("a","b","c")
allItems.addAll(list2)
I can use mutableList. it ok, but addAll result is 1,2,3,4,5,6,"a","b","c" right? I want that result is 1,"a",2,"b",3,"c",4,5
– Bahadır Bulduk
Mar 28 at 18:27
You're not specifying the sort order. Do you want the items to alternate or just be sorted?
– Hamed Momeni
Mar 28 at 19:40
add a comment
|
Your lists are of inconvertible types (Ints and Strings) so you have to have MutableList<Any>
so that you can add both types:
val allItems = mutableListOf<Any>(1,2,3,4,5)
val list2 = listOf("a","b","c")
allItems.addAll(list2)
I can use mutableList. it ok, but addAll result is 1,2,3,4,5,6,"a","b","c" right? I want that result is 1,"a",2,"b",3,"c",4,5
– Bahadır Bulduk
Mar 28 at 18:27
You're not specifying the sort order. Do you want the items to alternate or just be sorted?
– Hamed Momeni
Mar 28 at 19:40
add a comment
|
Your lists are of inconvertible types (Ints and Strings) so you have to have MutableList<Any>
so that you can add both types:
val allItems = mutableListOf<Any>(1,2,3,4,5)
val list2 = listOf("a","b","c")
allItems.addAll(list2)
Your lists are of inconvertible types (Ints and Strings) so you have to have MutableList<Any>
so that you can add both types:
val allItems = mutableListOf<Any>(1,2,3,4,5)
val list2 = listOf("a","b","c")
allItems.addAll(list2)
answered Mar 28 at 18:24
Hamed MomeniHamed Momeni
4,5007 gold badges53 silver badges90 bronze badges
4,5007 gold badges53 silver badges90 bronze badges
I can use mutableList. it ok, but addAll result is 1,2,3,4,5,6,"a","b","c" right? I want that result is 1,"a",2,"b",3,"c",4,5
– Bahadır Bulduk
Mar 28 at 18:27
You're not specifying the sort order. Do you want the items to alternate or just be sorted?
– Hamed Momeni
Mar 28 at 19:40
add a comment
|
I can use mutableList. it ok, but addAll result is 1,2,3,4,5,6,"a","b","c" right? I want that result is 1,"a",2,"b",3,"c",4,5
– Bahadır Bulduk
Mar 28 at 18:27
You're not specifying the sort order. Do you want the items to alternate or just be sorted?
– Hamed Momeni
Mar 28 at 19:40
I can use mutableList. it ok, but addAll result is 1,2,3,4,5,6,"a","b","c" right? I want that result is 1,"a",2,"b",3,"c",4,5
– Bahadır Bulduk
Mar 28 at 18:27
I can use mutableList. it ok, but addAll result is 1,2,3,4,5,6,"a","b","c" right? I want that result is 1,"a",2,"b",3,"c",4,5
– Bahadır Bulduk
Mar 28 at 18:27
You're not specifying the sort order. Do you want the items to alternate or just be sorted?
– Hamed Momeni
Mar 28 at 19:40
You're not specifying the sort order. Do you want the items to alternate or just be sorted?
– Hamed Momeni
Mar 28 at 19:40
add a comment
|
I think Eugenes answer already contains all you need to know to combine two lists (be it zip
or combining all elements).
In case you want to combine an arbitrary number of lists, one item per alternating list, you may also be interested in the following approach:
fun combine(vararg lists: List<*>) : List<Any> = mutableListOf<Any>().also
combine(it, lists.map(List<*>::iterator))
private tailrec fun combine(targetList: MutableList<Any>, iterators: List<Iterator<*>>)
iterators.asSequence()
.filter(Iterator<*>::hasNext)
.mapNotNull(Iterator<*>::next)
.forEach targetList += it
if (iterators.asSequence().any(Iterator<*>::hasNext))
combine(targetList, iterators)
Calling it then looks as follows and leads to the value seen in the comment:
combine(list1, list2) // List containing: 1, "a", 2, "b", 3, "c", 4, 5
combine(list1, list2, listOf("hello", "world")) // 1, "a", "hello", 2, "b", "world", 3, "c", 4, 5
A simplified approach to the second part of Eugenes answer could be implemented using following code; that, of course, isn't lazy anymore as you get a list back ;-) (but maybe you even translated it directly to a list, so you can also use this approach):
fun List<Any>.combine(other: List<Any>) : List<Any> = mutableListOf<Any>().also second.hasNext())
if (first.hasNext()) it.add(first.next())
if (second.hasNext()) it.add(second.next())
Calling it would work as follows:
list1.combine(list2)
add a comment
|
I think Eugenes answer already contains all you need to know to combine two lists (be it zip
or combining all elements).
In case you want to combine an arbitrary number of lists, one item per alternating list, you may also be interested in the following approach:
fun combine(vararg lists: List<*>) : List<Any> = mutableListOf<Any>().also
combine(it, lists.map(List<*>::iterator))
private tailrec fun combine(targetList: MutableList<Any>, iterators: List<Iterator<*>>)
iterators.asSequence()
.filter(Iterator<*>::hasNext)
.mapNotNull(Iterator<*>::next)
.forEach targetList += it
if (iterators.asSequence().any(Iterator<*>::hasNext))
combine(targetList, iterators)
Calling it then looks as follows and leads to the value seen in the comment:
combine(list1, list2) // List containing: 1, "a", 2, "b", 3, "c", 4, 5
combine(list1, list2, listOf("hello", "world")) // 1, "a", "hello", 2, "b", "world", 3, "c", 4, 5
A simplified approach to the second part of Eugenes answer could be implemented using following code; that, of course, isn't lazy anymore as you get a list back ;-) (but maybe you even translated it directly to a list, so you can also use this approach):
fun List<Any>.combine(other: List<Any>) : List<Any> = mutableListOf<Any>().also second.hasNext())
if (first.hasNext()) it.add(first.next())
if (second.hasNext()) it.add(second.next())
Calling it would work as follows:
list1.combine(list2)
add a comment
|
I think Eugenes answer already contains all you need to know to combine two lists (be it zip
or combining all elements).
In case you want to combine an arbitrary number of lists, one item per alternating list, you may also be interested in the following approach:
fun combine(vararg lists: List<*>) : List<Any> = mutableListOf<Any>().also
combine(it, lists.map(List<*>::iterator))
private tailrec fun combine(targetList: MutableList<Any>, iterators: List<Iterator<*>>)
iterators.asSequence()
.filter(Iterator<*>::hasNext)
.mapNotNull(Iterator<*>::next)
.forEach targetList += it
if (iterators.asSequence().any(Iterator<*>::hasNext))
combine(targetList, iterators)
Calling it then looks as follows and leads to the value seen in the comment:
combine(list1, list2) // List containing: 1, "a", 2, "b", 3, "c", 4, 5
combine(list1, list2, listOf("hello", "world")) // 1, "a", "hello", 2, "b", "world", 3, "c", 4, 5
A simplified approach to the second part of Eugenes answer could be implemented using following code; that, of course, isn't lazy anymore as you get a list back ;-) (but maybe you even translated it directly to a list, so you can also use this approach):
fun List<Any>.combine(other: List<Any>) : List<Any> = mutableListOf<Any>().also second.hasNext())
if (first.hasNext()) it.add(first.next())
if (second.hasNext()) it.add(second.next())
Calling it would work as follows:
list1.combine(list2)
I think Eugenes answer already contains all you need to know to combine two lists (be it zip
or combining all elements).
In case you want to combine an arbitrary number of lists, one item per alternating list, you may also be interested in the following approach:
fun combine(vararg lists: List<*>) : List<Any> = mutableListOf<Any>().also
combine(it, lists.map(List<*>::iterator))
private tailrec fun combine(targetList: MutableList<Any>, iterators: List<Iterator<*>>)
iterators.asSequence()
.filter(Iterator<*>::hasNext)
.mapNotNull(Iterator<*>::next)
.forEach targetList += it
if (iterators.asSequence().any(Iterator<*>::hasNext))
combine(targetList, iterators)
Calling it then looks as follows and leads to the value seen in the comment:
combine(list1, list2) // List containing: 1, "a", 2, "b", 3, "c", 4, 5
combine(list1, list2, listOf("hello", "world")) // 1, "a", "hello", 2, "b", "world", 3, "c", 4, 5
A simplified approach to the second part of Eugenes answer could be implemented using following code; that, of course, isn't lazy anymore as you get a list back ;-) (but maybe you even translated it directly to a list, so you can also use this approach):
fun List<Any>.combine(other: List<Any>) : List<Any> = mutableListOf<Any>().also second.hasNext())
if (first.hasNext()) it.add(first.next())
if (second.hasNext()) it.add(second.next())
Calling it would work as follows:
list1.combine(list2)
edited Mar 29 at 15:46
answered Mar 29 at 15:35
RolandRoland
12.3k1 gold badge17 silver badges45 bronze badges
12.3k1 gold badge17 silver badges45 bronze badges
add a comment
|
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55404428%2fhow-to-combine-two-different-length-lists-in-kotlin%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Join both list as objetc and then use a comparator kotlinlang.org/api/latest/jvm/stdlib/kotlin/-comparator/…
– cutiko
Mar 28 at 18:23
Can you give an example?
– Bahadır Bulduk
Mar 28 at 18:27