8
5

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のリスト(配列)型へのアクション

Posted at

はじめに

今、新アプリを制作している過程でリストをいじることが多いです。
これからもリストとは長いお付き合いになるので、価値がありそうなアクションを溜めておこうと思います。

アクションたち

要素挿入

List<int> nums = [0, 1, 2, 3, 4];
nums.add(0);
// nums = [0, 1, 2, 3, 4, 0];

int index=1;
nums.insert(index, 7);
// nums = [0, 7, 1, 2, 3, 4, 0];
// indexで指定する要素になるイメージ
// insert後 => nums[index] = 7;

部分配列取り出し

dart
int start = 1;
List<int> nums = [0, 1, 2, 3, 4];
List<int> part1 = nums.sublist(start);
// part1 = [1, 2, 3, 4];

int end = 3;
List<int> part2 = nums.sublist(start,end);
// part2 = [1, 2];
python
nums = [0, 1, 2, 3, 4]
part = nums[1:]
# part = [1, 2, 3, 4]

インデックス指定要素取り出し

dart
int index = 1;
List<int> nums = [0, 1, 2, 3, 4];
int n = nums.removeAt(index);
// n = 1;
// nums = [0, 2, 3, 4];

リスト全要素関数実行

List<int> nums = [0, 1, 2, 3, 4];
List<int> newNums = nums.map((n)=>n+1).toList();
//newNums = [1, 2, 3, 4, 5];
//nums = [0, 1, 2, 3, 4]; 変化なし

判定

List<int> nums = [0, 1, 2, 3, 4];
nums.contains(0); // true
nums.contains(5); // false

nums.isEmpty(); // false
nums.isNotEmpty(); // true

nums.remove(0); // true
// nums = [1, 2, 3, 4];
nums.remove(5); // false
// nums = [1, 2, 3, 4];

配列の長さ

List<int> nums = [0, 1, 2, 3, 4];
int length = nums.length();
// length = 5;

配列のソート

List<int> nums = [0, 1, 2, 3, 4];
nums.sort((a,b)=>b-a);
// nums = [4, 3, 2, 1, 0];

nums.sort(); //sort((a,b)=>a-b);
// nums = [0, 1, 2, 3, 4];

配列の逆転

List<int> nums = [0, 1, 2, 3, 4];
List<int> reverse = nums.reversed.toList();
//reverse = [4, 3, 2, 1, 0];

おわりに

大抵のアクションはVSCodeなどエディタ予測機能で出てきます。
便利にエディタを使っていきましょう。

8
5
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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?