2
2

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.

【Dart】Mapのvalueを使ってソートする

Posted at

Mapのvalueでソートしたい事があったので調査しました。

SplayTreeMap class
SplayTreeMapのfromにソートしたいmapとcompareを渡せばソートできるみたいです。

下記のようなオブジェクトを作成しました。属性idでソートする予定。

Object
class Employee{
  int id;
  String name;
  Employee(this.id,this.name);
}

最初の並び順は下記の様な感じです。

unSort
  Map<String,Employee> map = Map<String,Employee>();
  map['hoge'] = new Employee(1, "sato");
  map['huga'] = new Employee(3, "tanaka");
  map['piyo'] = new Employee(2, "yamashita");

  map.forEach((key, value) {
    print("key:"+key+" | id:"+value.id.toString()+" | name:"+value.name);
  });

出力

key:hoge | id:1 | name:sato
key:huga | id:3 | name:tanaka
key:piyo | id:2 | name:yamashita

ソート後のMapを作成し再度出力すると…

sorted
final sortedMap = SplayTreeMap.from(
    map, (a, b) => map[a].id.compareTo(map[b].id));

sortedMap.forEach((key, value) {
  print("key:"+key+" | id:"+value.id.toString()+" | name:"+value.name);
});

出力

flutter: key:hoge | id:1 | name:sato
flutter: key:piyo | id:2 | name:yamashita
flutter: key:huga | id:3 | name:tanaka

オホ
できましたね。

2
2
7

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?