List의 중복확인

𝙃𝙖𝙞𝙡𝙚𝙮·2022년 5월 26일
0

우당탕탕 자바8

목록 보기
2/4

✔ set 이용하기

불필요한 객체생성 꺼려짐

✔ 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("중복된 요소가 있습니다! 예외 발생시키기");
    }
}

출처: https://doing7.tistory.com/145

profile
ෆ 𝓋𝒾𝓈 𝓉𝒶 𝓋𝒾𝑒 ෆ

0개의 댓글