※ ArrayList(List)의 중복데이터 제거 방법
- List의 데이터를 확인하여 중복을 제거
- HashSet, TreeSet을 사용하여 중복을 제거
- HashSet, TreeSet는 Set 인터페이스를 구현하므로, 요소를 순서에 상관없이 저장하고 중복된 값은 저장하지 않습니다.
- 차이점은 TreeSet는기본적으로 오름차순으로 데이터를 정렬합니다.
- 3. Stream의 distinct() 메서드를 사용하여 중복을 제거
[소스코드]
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class ListDistinct {
public static void main(String[] args) {
List<String> originList = new ArrayList<String>();
List<String> resultList = new ArrayList<String>();
originList.add("1");
originList.add("1");
originList.add("가나다");
originList.add("가나다");
originList.add("ABC");
originList.add("ABC");
// List의 데이터를 확인하여 중복 제거
resultList = getDistinctLogic(originList);
// HashSet을 사용하여 중복 제거
// resultList = getDistinctHashSet(originList);
// TreeSet을 사용하여 중복 제거
// resultList = getDistinctTreeSet(originList);
// Stream의 distinct() 메서드를 사용하여 중복을 제거
// resultList = getDistinctStream(originList);
System.out.println(resultList);
}
/**
* List에 데이터를 확인하여 중복 제거
*/
public static List<String> getDistinctLogic(List<String> originList) {
List<String> resultList = new ArrayList<String>();
int originSize = originList.size();
for (int a = 0; a < originSize; a++) {
if (!resultList.contains(originList.get(a))) {
resultList.add(originList.get(a));
}
}
return resultList;
}
/**
* HashSet을 사용하여 중복 제거
*/
public static List<String> getDistinctHashSet(List<String> originList) {
List<String> resultList = new ArrayList<String>();
HashSet<String> distinctData = new HashSet<String>(originList);
resultList = new ArrayList<String>(distinctData);
return resultList;
}
/**
* TreeSet을 사용하여 중복 제거
*/
public static List<String> getDistinctTreeSet(List<String> originList) {
List<String> resultList = new ArrayList<String>();
TreeSet<String> distinctData = new TreeSet<String>(originList);
resultList = new ArrayList<String>(distinctData);
return resultList;
}
/**
* Stream을 사용하여 중복 제거
*/
public static List<String> getDistinctStream(List<String> originList) {
List<String> resultList = new ArrayList<String>();
resultList = originList.stream().distinct().collect(Collectors.toList());
return resultList;
}
}
[결과내용]
// 1. List의 데이터를 확인하여 중복 제거 결과 값
[1, 가나다, ABC]
// 2. HashSet을 사용하여 중복 제거 결과 값
[1, ABC, 가나다]
// 3. TreeSet을 사용하여 중복 제거 결과 값
[1, ABC, 가나다]
// 4. Stream의 distinct() 메서드를 사용하여 중복을 제거 결과 값
[1, 가나다, ABC]
'PROGRAMING > JAVA' 카테고리의 다른 글
Java와 DB 간 날짜 포맷 관리 방법 (0) | 2024.11.04 |
---|---|
[Java] 형 변환의 모든 것: 기본 타입과 문자열 변환 (0) | 2024.11.04 |
[Java] 유용하고 자주 사용하는 StringUtils 정보 (0) | 2022.08.31 |
[forEach] for문 roop 중지 처리 (0) | 2020.09.11 |
[TRY/CATCH] 예외처리 및 트랜잭션 처리 (0) | 2020.09.07 |