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

KotlinでMapとListをfor文で操作しよう!

Last updated at Posted at 2021-01-21

Key:Valueが1:1のMapをListにする

  // 1:1
  val map = mapOf("key1" to "val1", "key2" to "val2", "key3" to "val3")
  // mapのすべてのvalueが格納される
  val valueList = ArrayList(map.values)
  var list: MutableList<String>
  list = ArrayList()
  list.addAll(valueList)

1:1のMapを条件分岐でListに格納する

  val map = mapOf("key1" to "val1", "key2" to "val2", "key3" to "val3")
  val valueList = ArrayList(map.values)

  // key1のvalueがarray変数に格納される("val1")
  var araay = map.get("key1").toString()
  // itemは0からはじまる
  for (item in valueList.indices){
      // val1がvalueListにある場合はListに追加
      if (araay.contains(valueList[item])){
          list.add(valueList[item])
      }
  }

Mapのvalueを配列にしてネストさせる(1:n)

  // 1:n
  val mapArray = mapOf("keyX" to arrayOf("valA","valB", "valC").map { num -> num },
                       "keyY" to arrayOf("valD","valE").map { num -> num })
  val valueArrayList = ArrayList(mapArray.values)

1:nのMapを条件分岐でListに格納する

  // 1:n
  val mapArray = mapOf("keyX" to arrayOf("valA","valB", "valC").map { num -> num },
                       "keyY" to arrayOf("valD","valE").map { num -> num })
  val valueArrayList = ArrayList(mapArray.values)

  var araay = mapArray.get("keyX").toString()
  for (item in valueArrayList.indices) {
      // ネストしている配列の要素数だけループする
      for (i in valueArrayList[item].indices) {
          if (araay.contains(valueArrayList[item].get(i))) {
             list.add(valueArrayList[item].get(i))
          }
      }
  }
1
1
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
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?