1
1

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 5 years have passed since last update.

kotlinで2つの異なるListから重複するIDのものだけ抽出する

Posted at

これなに

備忘録。よく調べてよく答え見つからなくてよく特定の記事にたどり着くので完全自分用です

kotlinにおいて
別のdata classをgenericsにもつListに共通するIDを用いて
片方のdata class listを取得したいってときに使う

参考にした記事
https://qiita.com/amay077/items/9d2941283c4a5f61f302

前提

こんなdata class×2があるとします

data class Hoge {
  val id: Int,
  val title: String
}

data class Fuga {
  val id: Int,
  val title: String,
  val url: String
}

Hogeがマスタ、Fugaがユーザー選択するものとして
選択されているFugaListの id が共通なHogeListだけ取得するという場合を想定します

結論

val commonIdList = fugaList.flatMap { fuga -> hogeList.filter { hoge -> hoge.id == fuga.id } }

以上です

1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?