JAVA List 데이터 삭제 remove, removeAll, clear 사용 방법

List에서 데이터를 삭제하는 방법을 알아보겠습니다.

삭제를 하는 방법으로 remove, removeAll, clear 메서드를 사용할 수 있습니다.

각 메서드의 기본적인 내용은 다음과 같습니다.

  • remove – 하나의 요소를 삭제
  • clear – 요소를 모두 삭제
  • removeAll – 지정한 값 요소를 삭제

 

위 메서드를 응용해 조건과 일치하는 요소만 삭제하거나 범위를 지정해 삭제를 할 수도 있습니다.

 

remove

List에 들어 있는 하나의 요소를 삭제할 경우 요소의 순서를 지정하고 삭제하는 방법과 요소의 값을 지정하고 삭제하는 방법 2종류가 있습니다.

List에 들어 있는 index번호를 지정해 삭제하는 경우에는 remove메서드를 사용합니다.

remove메서드의 파라미터에는 index번호를 지정합니다.

또는 List내의 요소의 값을 지정해 삭제하고 싶은 경우에는 indexOf메서드를 같이 사용합니다.

indexOf로 그 요소의 index번호를 취득한 후 remove 메서드를 사용해 요소를 삭제합니다.

샘플 코드를 보면서 사용 방법을 확인해보겠습니다.

import java.util.ArrayList;
 
public class Main {
 
    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("Apple");       // ,1. "Apple"
        array.add("People");      // ,2. “People”
        array.add("Monkey");      // ,3. “Monkey”
        array.add("Banana");      // ,4. “Banana”
         
        //indexOf메서드에서 index번호를 취득 
        array.remove(array.indexOf("Monkey"));
        
        System.out.println(array);
    }
 
}

 

결과

[Apple, People, Banana]

 

샘플 코드에서는 요소 값을 지정해 먼저 해당 인덱스 위치를 찾아 삭제하는 예제입니다.

indexOf 메서드를 사용해 값이 “Monkey”의 요소의 index번호를 취득하고 있습니다.

remove메서드의 인수에 취득한 index번호를 지정해 삭제했습니다.

 

removeAll

removeAll메서드는 지정한 값만 List에서 모두 삭제합니다.

예를 들면 중복된 값을 가진 요소가 많아 그것만을 삭제하고 싶은 경우에 사용하면 편리합니다.

이러한 경우에는 removeAll메서드 인수에 Collection형 객체를 지정할 필요가 있습니다.

샘플 코드를 보면서 확인해보겠습니다.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Main {
 
    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<>();
        list1.add("a");
        list1.add("b");
        list1.add("c");
        list1.add("d");
        list1.add("e");
     
        // b, c, d를 삭제할 요소를 생성 
        List<String> set = new ArrayList<>();
        Collections.addAll(set, "b", "c", "d");
     
        // list1을 list2에 임시 저장 리스트
        List<String> list2 = new ArrayList<>(list1);
     
        System.out.println(list2);
     
        // list2에서 b, c, d를 삭제 
        list2.removeAll(set);
     
        // 삭제 후 요소를 모두 표시
        System.out.println("---------------------------");
        System.out.println(list2);
    }
 
}

 

결과

[a, b, c, d, e]
---------------------------
[a, e]

 

샘플 코드에서는 List내의 요소중 “a”,”e” 이외의 값을 모두 삭제하기 위해 “b”, “c”, “d” 값을 가진 List를 생성했습니다.

그리고 list1을 list2로 임시 저장시키고 removeAll메서드를 호출해 요소를 삭제했습니다.

결과를 보면 “b”, “c”, “d” 삭제된 것을 확인할 수 있습니다.

 

clear

clear메서드를 사용하면 List내의 요소가 모두 삭제됩니다.

샘플을 보면서 사용 방법을 확인해보겠습니다.

import java.util.ArrayList;
 
public class Main {
 
    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("Apple");       // ,1. "Apple"
        array.add("People");      // ,2. “People”
        array.add("Monkey");      // ,3. “Monkey”
        array.add("Banana");      // ,4. “Banana”
         
        array.clear();
 
        System.out.println("count : " + array.size());
    }
 
}

 

결과

count : 0

 

범위 지정 삭제

index번호의 범위를 지정해서 요소를 삭제할 수도 있습니다.

범위를 지정하고 삭제하는 방법을 보겠습니다.

이번 포스팅에서 사용할 방법은 subList메서드에서 범위를 지정하여 그 범위의 요소를 clear메서드에 설정하는 방법입니다.

subList메서드는 어떤 List에서 필요한 범위만 취득하고 새 List를 만들 경우에 사용합니다.

subList메서드의 첫 번째 파라미터로는 범위의 시작 index번호를 지정합니다.

그리고 두 번째 파라미터에는 삭제하고 싶은 마지막 index번호 + 1을 지정합니다.

subList메서드에서 범위를 먼저 지정하고 그 범위 요소를 clear메서드에서 사용하면 됩니다.

샘플 코드로 보면서 사용 방법을 확인해보겠습니다.

import java.util.ArrayList;
import java.util.List;
 
public class Main {
 
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("White");
        names.add("Yellow");
        names.add("Red");
        names.add("Blue");
        names.add("Black");
     
        // 삭제전 요소를 출력
        System.out.println(names);
     
        // index번호 1과 2를 삭제
        names.subList(1, 3).clear();
     
        // 삭제후 요소를 출력
        System.out.println("---------------------------");
        System.out.println(names);
    }
 
}

 

결과

[ White ,  Yellow ,  Red ,  Blue ,  Black ] 
---------------------------
[ White ,  Blue ,  Black ]

 

인덱스 1과 2의 값을 삭제했습니다.

인덱스 2번까지 지우기 위해 지우고 싶은 인덱스 번호에 +1을 지정했습니다.

List에서 값을 삭제하는 방법을 알아보았습니다.

삭제하는 방법으로는 값의 위치를 찾아 삭제하는 방법과 인덱스를 직접 지정해 삭제하는 방법 등 여러 가지가 있습니다.

또는 List를 전체 삭제하거나 범위를 지정해 삭제할 수도 있습니다.

상황에 맞는 방법을 찾아 사용하면 좋을 거 같습니다.

댓글