상세 컨텐츠

본문 제목

[JAVA] ArrayList 중복데이터 제거방법

java

by aries574 2020. 6. 26. 13:11

본문


자바에서는 객체를 담거나, 데이터를 담을때 흔하게 쓰이는게 ArrayList입니다.

이번에 알아볼 내용은 데이터를 비교해서 중복된 데이터면 삭제하는 것입니다.

1. 2개의 리스트를 만듭니다.

  ArrayList<String> infoList = new ArrayList<String>(); //등록된 데이터
 ArrayList<String> deleteList = new ArrayList<String>();//삭제할 데이터

2. 각각의 리스트에 데이터를 넣어줍니다.

 //등록 리스트에 데이터 추가
 infoList.add("a");
 infoList.add("b");
 infoList.add("c");


 //삭제 리스트에 데이터 추가
 deleteList.add("a");
 deleteList.add("b");

3. 중복된 데이터를 제거합니다.

a, b 라는 데이터를 infoList에서 삭제할 것입니다.
deleteList의 크기만큼 for문을 돌려서
deleteLis에서 꺼낸 값과 infoList에서 꺼낸값이 같다면 
infoList에서 해당 값을 삭제하는 것입니다.
 for(int i = 0; i < deleteList.size(); i++) {
 Iterator<String> iter = infoList.iterator();
           while(iter.hasNext()) {
               if(deleteList.get(i).equals(iter.next())) {
                   iter.remove();                   
               }
           }
 }
 System.out.println("arrChiceNmList: " + infoList);
반응형

관련글 더보기

댓글 영역