Dart リスト(配列)に条件を指定して値を削除する

Dartで、リスト(配列)に条件を指定して値を削除するコードを記述してます。「removeWhere」に条件を指定することで削除できます。また、「removeWhere」は「const」を指定したリストに対して実行するとエラーが発生します。
環境
- OS windows11 home
- Dart 2.18.1
条件を指定して値を削除
条件を指定して値を削除するには「removeWhere」を使用します。
リスト.removeRange(関数で条件指定)
実際に使用して、「3未満」の値を削除してみます。
void main() {
var list = [1, 2, 3, 4, 5];
list.removeWhere((value) => value < 3);
print(list); // [3, 4, 5]
}
実行結果を見ると、削除されていることが確認できます。

例えば、3文字の文字列を削除する場合は、以下のように長さを条件に指定します。
void main() {
var list = ['one', 'two', 'three', 'four'];
list.removeWhere((value) => value.length == 3);
print(list); // [three, four]
}
定数
「const」で宣言したリストを削除しようとすると、エラー「Unsupported operation: Cannot remove from an unmodifiable list」が発生します。
void main() {
const list = ['one', 'two', 'three', 'four'];
list.removeWhere((value) => value.length == 3);
print(list);
}
Unhandled exception:
Unsupported operation: Cannot remove from an unmodifiable list
#0 UnmodifiableListMixin.removeWhere (dart:_internal/list.dart:139:5)
#1 main (file:///c:/sample/main.dart:4:8)
#2 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
「final」の場合は、メモリ領域は変更できるためエラーにはなりません。
void main() {
final list = ['one', 'two', 'three', 'four'];
list.removeWhere((value) => value.length == 3);
print(list); // [three, four]
}
-
前の記事
コマンドプロンプトでディスクの空き容量を確認する方法 2024.10.24
-
次の記事
kotlin Listの要素の合計値を求める 2024.10.24
コメントを書く