🐡
Listからnullを取り除く方法(Dart)
List<T?>からnullを取り除く時の方法あれこれ。
List<T?>からList<T>を生成する場合
List.whereTypeを使う
List<int?> nullableList = [1, null, 3, null, 5];
List<int> nonnullableList = nullableList.whereType<int>().toList();
collectionのwhereNotNullを使う
collectionライブラリのwhereNotNullを使う。
List<int?> nullableList = [1, null, 3, null, 5];
List<int> nonnullableList = nullableList.whereNotNull().toList();
速度について
1000000回上記コードを実行した時の時間は下記の通りでした。
方法 | 実行時間(/ms) |
---|---|
whereType | 93 |
whereNotNull | 145 |
whereNotNullのパフォーマンスが悪くでたのですが、whereType,whereNotNullで最後のIterableからListに変換する部分を削ると13ms,14msとほぼ同じパフォーマンスが出たのでメモリ状況とかが影響したのかも。要検証。
List<T?>からnullを削除する場合
List.removeWhereを使う
他と異なりList.removeWhereのみ元Listに副作用があります。
List<int?> nullableList = [1, null, 3, null, 5];
nullableList.removeWhere((e) => e == null);
List<T?>からnullを削除したIterable<T?>を生成する場合
List.whereを使う
List<int?> nullableList = [1, null, 3, null, 5];
nullableList.where((e) => e != null);
参考:
Discussion