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?

Android開発で出てくるmapまとめ(自分用メモ)

Posted at

Android開発でKotlinやJavaを触っていると至る所でmapが出てきてややこしかったのでまとめてみます。

コレクション型としてのMap

キーと値のペアを保持するコレクションの一種。
mapOf()で値を生成する。

test.kt
    val test: Map<String, String> = mapOf("key1" to "value1", "key2" to "value2")
    println(test["key1"]) // value1

コレクションの.map

すでに存在するコレクションを元に新たなコレクションを生成する。

test.kt
    val integers = listOf(1, 2, 3)

    val twiceIntegers = integers.map {
        it * 2 // <- 各要素は"it"で取得できる
    }

    println(integers) // [1, 2, 3]
    println(twiceIntegers) // [2, 4, 6]

LiveDataの.map

あるLiveDataの値が変わった時に他のLiveDataの値も変えたいという時に使う。

TestViewModel.kt
val useId = MutableLiveData<Int>()
val userName: LiveData<String> = Transformations.map(userId) {  id -> 
    "userName: ${id} "
}

Coroutine flowの.map

Flowの各イベントを元に新しいFlowを生成する。

test.kt
runBlocking {
    val numbers = (1..5).asFlow()
    val doubledNumbers = numbers.map { it * 2 }
    doubledNumbers.collect {
        println(it) // 246810が順に出力される
    }

RxJavaのmap

流れてきたデータを変換する。

test.kt
Observable.range(1, 5)
        .map(i -> i * 2)
        .subscribe(System.out::print); // 246810

型としてのMap以外はどれも「元の値に何か操作を加えて新しい値を生成する」という時に使われるようです。

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?