どうも、ちょげ(@chogetarou)です。
リスト(List)の特定の要素を全て削除する方法を紹介します。
方法
リスト(List)の特定の要素を全て削除する方法は、3つあります。
remove()
ひとつめは、remove()を使う方法です。
まず、while()を記述します。
while()の条件でリストからremove()を呼び出します。
そして、remove()の引数に削除する要素を指定します。
//list=対象のリスト, item=削除する要素
while(list.remove(item));
上記のremove()は、呼び出したリスト(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);
while(nums.remove("three"));
System.out.println("変更後:" + nums);
}
}
出力:
変更前:[three, one, two, three, four, three, five]
変更後:[one, two, four, five]
removeAll()
ふたつめは、removeAll()を使う方法です。
まず、リストからremoveAll()を呼び出します。
そして、removeAll()の引数に削除する要素を持つコレクションを指定します。
//list=対象のリスト, collection=削除する要素を持つコレクション
list.removeAll(collection);
上記のremoveAll()は、呼び出したリスト(List)から引数のコレクションが持つ要素を削除します。
使用例1
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) throws Exception {
ArrayList<String> nums = new ArrayList<String>(5);
nums.add("three");
nums.add("one");
nums.add("two");
nums.add("three");
nums.add("three");
nums.add("four");
nums.add("five");
nums.add("three");
System.out.println("変更前:" + nums);
nums.removeAll(Collections.singleton("three"));
System.out.println("変更後:" + nums);
}
}
出力:
変更前:[three, one, two, three, three, four, five, three]
変更後:[one, two, four, five]
使用例2
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("five", "one", "two", "three", "four", "three", "five", "five"));
System.out.println("変更前:" + nums);
nums.removeAll(Arrays.asList("three", "five"));
System.out.println("変更後:" + nums);
}
}
出力:
変更前:[five, one, two, three, four, three, five, five]
変更後:[one, two, four]
removeIf()
みっつめは、removeIf()を使う方法です。
まず、リストから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]
まとめ
リスト(List)の特定の要素を全て削除する方法は、次の3つです。
- remove()を使う方法
while(list.remove(item));
- removeAll()を使う方法
list.removeAll(collection);
- removeIf()を使う方法
list.removeIf(c -> c == item);
コメント