Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- redis + spring boot 함께
- 엔티티 코드 치환
- jQuery
- 톰캣
- Linux
- 리눅스
- 자바
- Docker Compose
- Java
- mysql
- aws elasticache 활용
- js
- 특수문자 치환
- springboot+redis
- architecture
- insert
- 초단위
- catalina.out
- javascript
- 만들면서 배우는 클린 아키텍처
- 제이쿼리
- docker 컨테이너로 띄우기
- 정규식
- Entity Code 치환
- select
- for문
- Tomcat
- feignClient
- sftp
- 자바스크립트
Archives
- Today
- Total
꾸준하게, 차근차근
[Java] 배열 내 요소 중복여부 체크 본문
반응형
1. Set
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,4,5,5,6);
Set<Integer> set = new HashSet<Integer>(list);
System.out.println(list.size());
System.out.println(set.size());
if( list.size() != set.size() ) {
System.out.println("배열 내 중복 요소 존재");
}
}
Set은 중복을 허용하지 않는 자료구조이다.
리스트를 Set으로 변환한 후 두 객체의 사이즈를 비교하여 사이즈가 일치하지 않는다면 리스트 내 중복 요소가 존재하고 있는 것입니다.
2. Stream.distinct()
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,4,5,5,6);
System.out.println(list.size());
System.out.println(list.stream().distinct().count());
if( list.size() != list.stream().distinct().count() ) {
System.out.println("배열 내 중복 요소 존재");
}
}
Stream.distinct()는 배열 내 중복 요소를 제거합니다.
Stream.count()는 Stream의 사이즈를 리턴합니다.
따라서 Stream.distinct().count()는 배열 내 중복 요소가 제거된 사이즈를 리턴하기 때문에 두 객체의 사이즈를 비교하여 사이즈가 일치하지 않는다면 리스트 내 중복 요소가 존재하고 있는 것입니다.
3. 중첩 반복문
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,4,5,5,6);
for( int i=0; i<list.size(); i++ ) {
for( int j=0; j<i; j++ ) {
if( list.get(i) == list.get(j) ) {
System.out.println("배열 내 중복 요소 존재");
return;
}
}
}
}
이중 For문을 이용하여 배열의 중복 요소가 존재하고 있는지를 확인합니다.
🙏 참조 ::
반응형
'Java' 카테고리의 다른 글
[Java] SFTP 파일 전송(업로드) 구현(JSch 사용) (0) | 2022.04.26 |
---|---|
[Java] 파일 Zip파일로 압축하여 업로드(암호설정) 구현(zip4j 사용) (0) | 2022.04.26 |
[Java] 배열에 특정 값 존재(포함)여부 체크 (0) | 2022.03.19 |
[Java] 정규식(Regular Expression) (0) | 2022.03.19 |
[Java] 문자열 시분초 -> 초단위로 변환(timeToSec) 구현 (0) | 2021.10.15 |