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?

【Kotlin】コレクション操作関数まとめ

Last updated at Posted at 2025-09-30

仕事でよく使用するコレクション操作のまとめ。

map

要素を変換する

data class User(val id: Int, val name: String)

val users = listOf(
    User(1, "Taro"),
    User(2, "Jiro")
)

// 名前のリストを取得
val names = users.map { it.name }

println(names) // [Taro, Jiro]

filter

条件が一致する要素のみ抽出

data class User(val id: Int, val name: String, val isActive: Boolean)

val users = listOf(
    User(1, "Taro", true),
    User(2, "Jiro", false)
)

// アクティブなユーザーのみ取得
val activeUsers = users.filter { it.isActive }

println(activeUsers) // [User(id=1, name=Taro, isActive=true)]

groupBy

特定のキーでグループ化

data class Order(val id: Int, val status: String)

val orders = listOf(
    Order(1, "shipped"),
    Order(2, "pending"),
    Order(3, "shipped")
)

// ステータスごとにグループ化
val grouped = orders.groupBy { it.status }

println(grouped)
/*
{
  shipped=[Order(id=1, status=shipped), Order(id=3, status=shipped)],
  pending=[Order(id=2, status=pending)]
}
*/

sortBy

特定のプロパティでソートする

data class Product(val id: Int, val name: String, val price: Int)

val products = listOf(
    Product(1, "A", 500),
    Product(2, "B", 300),
    Product(3, "C", 400)
)

// 価格の昇順にソート
val sortedByPrice = products.sortedBy { it.price }

// 降順にソート
// val sortedDesc = products.sortedByDescending { it.price }


println(sortedByPrice)
/*
[
  Product(id=2, name=B, price=300),
  Product(id=3, name=C, price=400),
  Product(id=1, name=A, price=500)
]

distinctBy

特定のキーで重複を除外する

data class User(val id: Int, val name: String)

val users = listOf(
    User(1, "Taro"),
    User(2, "Jiro"),
    User(1, "Taro")
)

// IDが重複しているユーザーを除外(最初の1つだけ残す)
val distinctUsers = users.distinctBy { it.id }

println(distinctUsers)
// [User(id=1, name=Taro), User(id=2, name=Jiro)]

any/all

条件に一致するか

val numbers = listOf(1, 2, 3, 4)

// 1つでも偶数があるか
val hasEven = numbers.any { it % 2 == 0 } // true

// すべて正の数か
val allPositive = numbers.all { it > 0 } // true

flatMap

ネストされたリストを1段にフラットに

data class TagItem(val name: String, val tags: List<String>)

val items = listOf(
    TagItem("A", listOf("x", "y")),
    TagItem("B", listOf("y", "z"))
)

val allTags = items.flatMap { it.tags }

println(allTags) // [x, y, y, z]

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?