CodeGym /Java Blog /무작위의 /Java의 ArrayList removeAll() 메서드
John Squirrels
레벨 41
San Francisco

Java의 ArrayList removeAll() 메서드

무작위의 그룹에 게시되었습니다
Java의 ArrayList removeAll() 메서드는 이름에서 알 수 있듯이 적절한 ArrayList 에서 모든 요소를 ​​제거하지 않습니다 . 이 작업이 필요한 경우 ArrayList clear() 메서드를 사용하십시오. clear() 와 달리 removeAll () 메서드는 지정된 목록에서 다른 컬렉션에 포함된 모든 항목을 제거합니다.

removeAll() 구문 및 선언

메소드 구문은 다음과 같습니다.

boolean removeAll(Collection<?> c)
여기서 c 는 이 목록에서 제거할 요소를 포함하는 컬렉션입니다. 이 메서드는 호출 결과로 이 목록이 변경된 경우 true를 반환합니다. 또한 예외를 발생시킬 수 있습니다. ClassCastException — 이 목록의 요소 클래스가 지정된 컬렉션과 호환되지 않는 경우 NullPointerException — 목록에 null 요소가 포함되어 있고 지정된 컬렉션이 null 요소를 허용하지 않거나 지정된 컬렉션이 null인 경우

removeAll() 코드 예제

소셜 네트워크에 친구 목록이 있다고 가정해 보겠습니다. 뭐, 지금은 일상입니다. 또한, 당신이 꼼꼼한 사람이라고 가정하고, 당신의 적이 당신의 소셜 네트워크 친구 사이에 있는지 여부에 관계없이 특별한 적 목록에 모든 악의를 품은 사람들을 입력하십시오. 악의를 품은 모든 사람의 친구 목록을 지우기로 결정했습니다. removeAll () 메서드는 확실히 도움이 될 것입니다.

import java.util.ArrayList;
import java.util.List;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

           
           List<String> friendList = new ArrayList<String>();

           // use add() method to add friends into your friend list
           friendList.add("Alex");
           friendList.add("Ivy");
           friendList.add("Victor");
           friendList.add("Peter");
           friendList.add("Lenny");
           friendList.add("Olly");
           friendList.add("Stu");
           friendList.add("Scott");
           friendList.add("Olivia");

           System.out.println("My old friend list: "+ friendList);

           //create and add elements to foe list 
           List<String> foeList = new ArrayList<String>();

           foeList.add("Ben");
           foeList.add("Scott");
           foeList.add("Chuck");
           foeList.add("Olly");
           foeList.add("Sam");
           System.out.println("All my enemies: "+ foeList);

           //remove all foeList elements from friendList list if they exist
           friendList.removeAll(foeList);
           System.out.println("new friend List without foes: "+ friendList);
       }
   }
출력은 다음과 같습니다.
내 오랜 친구 목록: [Alex, Ivy, Victor, Peter, Lenny, Olly, Stu, Scott, Olivia] 내 모든 적: [Ben, Scott, Chuck, Olly, Sam] 적이 없는 새 친구 목록: [Alex, Ivy, 빅터, 피터, 레니, 스튜, 올리비아]
보시다시피 메서드는 적 Olly와 Scott을 삭제했습니다. 친구 목록에 벤, 척, 샘이 없었습니다. removeAll() 메서드 선언 에 따라 다른 목록의 값뿐만 아니라 임의 컬렉션의 값도 목록에서 삭제할 수 있다는 사실을 알아차렸을 것입니다. HashMap 을 예로 들어보겠습니다 . 이 경우 예를 들어 값 (removeAll(collection.values()) 또는 키 (removeAll(collection.keySet()))와 일치하는 레코드를 제거할 것임을 명시적으로 표시해야 합니다 . 친구 중 모든 소녀의 이름이 포함된 HashMap , friendList 에는 소년만 남겨야 합니다.(왜 이것이 필요한지 모르겠지만 당신은 결코 모릅니다). 예전 친구 목록으로 돌아가서 여자 HasMap 을 만들고 이름이 HashMap 의 값으로 쓰여진 모든 여자 친구를 친구 목록에서 제거해 봅시다 .

import java.util.*;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

          // create an empty array list and full it up using Java 9 Factory Methods  in one line
List<String> friendList= new ArrayList<>(List.of("Alex", "Ivy", "Victor", "Peter", "Lenny", "Olly", "Stu", "Scott", "Olivia"));

           System.out.println("My old friend list: "+ friendList);

           // Creating hashMap with girls keys and names also using using Java 9 Factory Methods   
           Map<Integer, String> girls = new HashMap<>(Map.of(1, "Olly", 2, "Olivia", 3, "Loe", 4, "Ivy"));
           friendList.removeAll(girls.values());
           System.out.println("boys only friendList: " + friendList);
       }
   }
결과는 다음과 같습니다.
내 오랜 친구 목록: [Alex, Ivy, Victor, Peter, Lenny, Olly, Stu, Scott, Olivia] 소년만 친구 목록: [Alex, Victor, Peter, Lenny, Stu, Scott]

일부 특별한 경우

이 기사의 시작 부분에서 목록에서 모든 값을 제거하려면 ArrayList clear() 메서드 를 사용해야 한다고 썼습니다 . 하지만 물론 이를 위해 removeAll() 메서드를 사용할 수도 있습니다. 당신은 아마도 이것을 하는 방법을 이미 짐작했을 것입니다:

myList.RemoveAll (myList);
예를 들어 보겠습니다. 소시오패스에 맞게 friendList 전체를 비웁니다.

 import java.util.*;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

           // create an empty array list and full it up using  Java 9 Factory Methods  in one line
           List<String> friendList= new ArrayList<>(List.of("Alex", "Ivy", "Victor", "Peter", "Lenny", "Olly", "Stu", "Scott", "Olivia"));
           System.out.println("My old friend list: "+ friendList);

           friendList.removeAll(friendList);
           System.out.println("my new empty friendlist...:" + friendList);
       }
   }
결과는 다음과 같습니다.
소년 전용 친구 목록: [Alex, Victor, Peter, Lenny, Stu, Scott] 빈 새 친구 목록...:[]
최소한 ArrayList 에서 null 컬렉션 요소를 제거해 봅시다 .

import java.util.*;

public class RemoveAll2Example {
  
       public static void main(String[] args) {

           List<String> friendList = new ArrayList<>(List.of("Alex", "Ivy", "Victor", "Peter", "Lenny", "Olly", "Stu", "Scott", "Olivia"));
           System.out.println("My old friend list: "+ friendList);

           // we are happy not to have foes 
           List<String> foeList = null;
          
           //trying to remove all foeList elements from friendList list 
            friendList.removeAll(foeList);
            System.out.println("my new friendlist:" + friendList);
       }
   }
removeAll() 메서드 정의 에 따르면 출력에 예외가 있습니다.
내 오랜 친구 목록: [Alex, Ivy, Victor, Peter, Lenny, Olly, Stu, Scott, Olivia] "main" 스레드의 예외 java.lang.NullPointerException
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION