Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
425 views
Welcome To Ask or Share your Answers For Others

1 Answer

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...