9
3

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のMapのkey, valueでそれぞれソートする

Posted at

下記のようなMapがあると仮定する。

val map: Map<Int, String> = mapOf<Int, String>(
    2 to "CCC",
    1 to "AAA",
    3 to "EEE",
    5 to "DDD",
    4 to "BBB"
)

Mapをそのまま印字する


println(map)

{2=CCC, 1=AAA, 3=EEE, 5=DDD, 4=BBB}

Mapのkeyでソートする

val result = map.toSortedMap()
println(result)

{1=AAA, 2=CCC, 3=EEE, 4=BBB, 5=DDD}

Mapのvalueでソートする

val result = map.toList().sortedBy { it.second }.toMap()
println(result)

{1=AAA, 4=BBB, 2=CCC, 5=DDD, 3=EEE}
9
3
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
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?