Dart Mapにキーが存在しない場合にキーを追加する

Dartで、Mapにキーが存在しない場合にキーを追加するコードを記述してます。「putIfAbsent」を使用してキーと値を指定することで可能です。
環境
- OS windows11 home
- Dart 2.18.4
Mapにキーが存在しない場合にキーを追加
Mapにキーが存在しない場合にキーを追加するには
1. 「putIfAbsent」でキー名と値を指定
することで可能です。
Map.putIfAbsent(キー名, () => 値);
実際に、使用して追加してみます。
void main() {
var map = <int, String>{
1: 'one',
2: 'two',
3: 'three',
};
map.putIfAbsent(1, () => 'foo');
map.putIfAbsent(4, () => 'four');
map.putIfAbsent(5, () => 'five');
print(map); // {1: one, 2: two, 3: three, 4: four, 5: five}
}
実行結果を見ると、重複していないキー以外が追加されていることが確認できます。

ループ処理
ループ処理を使用して、複数の値を追加することも可能です。
void main() {
var map = <int, String>{
1: 'one',
2: 'two',
3: 'three',
};
for (var key in [4, 5, 6]) {
map.putIfAbsent(key, () => 'foo');
}
print(map); // {1: one, 2: two, 3: three, 4: foo, 5: foo, 6: foo}
}
-
前の記事
Ubuntu22.10 起動しているサービスを一覧で確認する 2022.11.25
-
次の記事
Google Colaboratory 別のファイルを開くショートカットキー 2022.11.25
コメントを書く