9
1

More than 3 years have passed since last update.

【Salesforce, Apex】Listを繰り返し、要素を削除していく

Last updated at Posted at 2020-12-19

リストをループさせ任意の項目だけ削除していく実装をした際に以下実装でしていこうとしました。

for (Integer i = 0; i < this.productList.size(); i++) {
    if (this.productList.get(i).isRemove) {
        this.productList.remove(i);
    }
}

しかし、これだと期待する動きにならない。
一個スルーされてしまう要素が出てしまいます。

何故

リストのサイズが3で以下のような中身だったとします。

List{
    0 => productObj1,
    1 => productObj2,
    2 => productObj3
}

1回目のループで削除の分岐に入り削除されると以下のような形になります。

List{
    0 => productObj2,
    1 => productObj3
}

indexが振られ直されています。
ループカウンタの i はというと 0 -> 1 にインクリメントされてます。
まぁ当たり前ですよね

2回目のループでも削除されたとします。
中身はこんな感じになります。

List{
    0 => productObj2
}

そしてループ終了。
削除を免れたproductObj2。許しません。

案1 カウンタ変数をデクリメントする。

for (Integer i = 0; i < this.productList.size(); i++) {
    if (this.productList.get(i).isRemove) {
        this.productList.remove(i);
        i--;
    }
}

案2 whileバージョン

削除した時にはカウンタ変数をインクリメントさせません。

Integer i = 0;
while (i < this.productList.size()) {
    if (this.productList.get(i).isRemove) {
        this.productList.remove(i);
        continue; // continueしてインクリメントさせないようにする
    }
    i++;
}

案3 ケツから削除

あとはこんな方法も?
合計数(-1)をカウンタ変数に入れデクリメントしながらループさせ、ケツから削除していきましょう。

for (Integer i = this.productList.size() - 1; i >= 0; i--) {
    if (this.productList.get(i).isRemove) {
        this.productList.remove(i);
    }
}
9
1
1

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
9
1