>  기사  >  Java  >  Java의 ArrayList 객체에서 중복 요소를 제거하는 방법은 무엇입니까?

Java의 ArrayList 객체에서 중복 요소를 제거하는 방법은 무엇입니까?

王林
王林앞으로
2023-08-30 20:29:10434검색

Java의 ArrayList 객체에서 중복 요소를 제거하는 방법은 무엇입니까?

인터페이스 세트는 중복 요소를 허용하지 않습니다. 이 인터페이스의 add() 메소드는 요소를 승인하고 이를 Set 객체에 추가하며, 추가에 성공하면 true를 반환하고, 이 메소드를 사용하여 기존 요소를 추가하려고 하면 추가 작업이 실패하고 false를 반환합니다.

따라서 ArrayList 객체에서 중복 요소를 제거하려면 다음 단계를 따르세요.

  • 필요한 ArrayList를 가져오거나 생성하세요.

  • 빈 집합 개체를 만듭니다.

  • ArrayList 개체의 모든 요소를 ​​개체 설정에 추가해 보세요.

  • ArrayList의 내용을 지우려면 Clear() 메서드를 사용하세요.

  • 이제 addAll() 메서드를 사용하여 설정된 개체의 내용을 ArrayList에 다시 추가합니다.

데모

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class RemovingDuplicates {
   public static void main(String[] args){
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFX");
      list.add("Java");
      list.add("JavaFX");
      list.add("OpenCV");
      list.add("Java");
      list.add("JOGL");
      list.add("JOGL");
      list.add("HBase");
      list.add("Flume");
      list.add("HBase");
      list.add("Impala");
      System.out.println("Contents of the Array List : \n"+list);
      //Retrieving Iterator object of the ArrayList class
      Iterator<String> it = list.iterator();
      //Creating an empty Set object
      Set<String> set = new HashSet<String>();
      //Adding elements of the ArrayList to the Set object
      while(it.hasNext()) {
         set.add(it.next());
      }
      //Removing all the elements from the ArrayList
      list.clear();
      //Adding elements of the set back to the list
      list.addAll(set);
      System.out.println("Contents of the Array List after removing duplicate elements: \n"+list);
   }
}

출력

Contents of the Array List :
[JavaFX, Java, JavaFX, OpenCV, Java, JOGL, JOGL, HBase, Flume, HBase, Impala]
Contents of the Array List after removing duplicate elements:
[JavaFX, Java, OpenCV, JOGL, Flume, Impala, HBase]

위 내용은 Java의 ArrayList 객체에서 중복 요소를 제거하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제