0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Kotlin】リストに追加 / リストの結合

Last updated at Posted at 2024-02-03

1. add() : 単一の値を追加する

※Mutable(可変)なリストでないとadd()は使用不可であることに注意!

fun main(){
    val list1 = mutableListOf(1, 2, 3)

    list1.add(4)

    println("結合結果 : $list1")
}

Output:

結合結果 : [1, 2, 3, 4]

2. addAll() : 2つのリストを結合

※Mutable(可変)なリストでないとaddAll()は使用不可であることに注意!

fun main(){
    val list1 = listOf(1, 2, 3)
    val list2 = listOf(1, 4, 5, 6)

    val joinedList = mutableListOf()
    joinedList.addAll(list1)
    joinedList.addAll(list2)

    println("結合結果 : $joinedList")
}

Output:

結合結果 : [1, 2, 3, 1, 4, 5, 6]

3. Plus演算子 : 2つのリストを結合

Plus演算子を用いた結合
fun main(){
    val list1 = listOf(1, 2, 3)
    val list2 = listOf(1, 4, 5, 6)

    val joinedList = list1 + list2

    println("結合結果 : $joinedList")
}

Output:

結合結果 : [1, 2, 3, 1, 4, 5, 6]

4. plus() : 2つのリストを結合

Plus演算子を用いた結合
fun main(){
    val list1 = listOf(1, 2, 3)
    val list2 = listOf(1, 4, 5, 6)

    val joinedList = list1.plus(list2)

    println("結合結果 : $joinedList")
}

Output:

結合結果 : [1, 2, 3, 1, 4, 5, 6]

5. union() : 重複削除かつリストの結合

fun main(){
    val list1 = listOf(1, 2, 3)
    val list2 = listOf(1, 2, 4, 5, 6)

    val joinedList = list1.union(list2)

    println("結合結果 : $joinedList")
}

Output:

重複した値1を削除したうえで結合した結果が返却される

結合結果 : [1, 2, 3, 4, 5, 6]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?