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?

More than 3 years have passed since last update.

Dartでint型Listの昇順/降順ソート

Last updated at Posted at 2021-09-18

確認環境

  • OS: Windows 10 Pro
  • Dart: 2.7.21

昇順ソート

sort()メソッドを使うとデフォルトで昇順ソートされる

final list1 = [4, 1, 2, 3];
list1.sort();
print(list1); // -> [1, 2, 3, 4]

降順ソート

素直にComparetorを使うパターン

sort()メソッドのデフォルトが、a.compareTo(b)の結果(-1,0,1)で大小比較しているので、それに-1を掛けたものをComparetorとして渡してあげれば逆順になる

final list2 = [4, 1, 2, 3];
list2.sort((a,b) => -1 * a.compareTo(b));
print(list2); // -> [4, 3, 2, 1]

昇順ソート後にreverseするパターン

昇順ソート後にreversedの値を取得することでも逆順のリストが得られる(無駄なことしてる感はあるけど)2

final list3 = [4, 1, 2, 3];
list3.sort();
print(list3.reversed.toList()); // -> [4, 3, 2, 1]

ちなみにsort()は値を書き換えるけどreversedは書き換えない

print(list3);                   // -> [1, 2, 3, 4] 

参考

sort method - List class - dart:core library - Dart API

  1. 確認時点の最新(2.14.2)のドキュメントもそれほど中身変わってなかったので問題なく動くとは思う -> sort method - List class - dart:core library - Dart API

  2. compareToが分かりづらいと思ってしまう人間なので、逆順にする程度の単純なソートであればむしろこっちの方がぱっと見で何してるのか分かりやすいと個人的には思ってしまう。(見易さだけで言えば)

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?