[Java]removeIf()でリスト(List)の特定の要素を全て削除するには?

Java

どうも、ちょげ(@chogetarou)です。

removeIf()でリスト(List)の特定の要素を全て削除する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

removeIf()でリスト(List)の特定の要素を全て削除するには、引数を使います。

まず、リストからremoveIf()を呼び出します。

そして、removeIf()の引数に、引数と特定の要素が等しい時に「true」となる条件式を返すラムダ式を指定します。

//list=対象のリスト, item=削除する要素
list.removeIf(c -> c == item);

上記のremoveIf()は、呼び出したリスト(List)から特定の要素を全て削除します。

スポンサーリンク

使用例

import java.util.ArrayList;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) throws Exception {
        ArrayList<String> nums = new ArrayList<String>(Arrays.asList("three", "one", "two", "three", "four", "three", "five"));
        
        System.out.println("変更前:" + nums);
        
        nums.removeIf(c -> c == "three");
        
        System.out.println("変更後:" + nums);
    }
}
出力:
変更前:[three, one, two, three, four, three, five]
変更後:[one, two, four, five]

コメント

タイトルとURLをコピーしました