Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

DOing

[Java] 리스트 내 요소 중복 체크 본문

Java & Kotlin

[Java] 리스트 내 요소 중복 체크

mangdo 2021. 9. 14. 15:32

새 프로젝트의 요구사항 중에 '리스트 내 요소들은 중복되지 않아야 합니다'가 있었습니다.

리스트 내 요소들이 중복되는지를 확인하고, 있다면 예외를 발생시켜야 했습니다.

이와 같은 상황을 어떻게 자바에서 해결해야할지 알아보도록 하겠습니다.

 

 

 


1. Set 이용

: Set은 중복을 허용하지 않는 자료구조 입니다.

: 리스트를 set으로 변환해서 크기를 비교합니다. 크기가 달라졌다면 리스트에 중복된 요소가 있었다는 것을 의미합니다.

    public static void main(String[] args) {

        List<Integer> numList = Arrays.asList(1,1,2,3,4,5);
        // Set 으로 변환
        Set<Integer> numSet = new HashSet<>(numList);

        if(numSet.size()!= numList.size()){
            System.out.println("중복된 요소가 있습니다! 예외 발생시키기");
        }
    }

 

 

2. Stream.distinct() 이용

: Stream.distinct()은 stream의 중복을 모두 제거합니다.

: Stream.count()는 stream의 사이즈를 리턴합니다.

: 기존의 리스트 크기와 Stream.distinct().count()가 다르다면 리스트에 중복된 요소가 있었다는 것을 의미합니다.

    public static void main(String[] args) {

        List<Integer> numList = Arrays.asList(1,1,2,3,4,5);
        if(numList.size() != numList.stream().distinct().count()){
            System.out.println("중복된 요소가 있습니다! 예외 발생시키기");
        }
    }

 

 

 

3. 중첩 반복문 이용 

: 이중 for문을 이용해서 중복을 확인합니다.

    public static void main(String[] args) {

        List<Integer> numList = Arrays.asList(1,1,2,3,4,5);
        
        for (int i = 0; i < numList.size(); i++) {
            for (int j = 0; j < i; j++) {
                if (numList.get(i).equals(numList.get(j))) {  // 중복 검사
                    System.out.println("중복된 요소가 있습니다! 예외 발생시키기");
                    return;
                }
            }
        }
    }

 

 

 

 

 

참고 사이트:

https://codechacha.com/ko/java-check-if-list-contains-duplicates/

https://seeminglyjs.tistory.com/247