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
- 스프링 부트
- 정처기
- 호이스팅
- 분할정복
- 레디스
- 스프링 시큐리티
- 실행 컨텍스트
- 캐시
- VMware
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- spring security
- 다이나믹프로그래밍
- 스프링부트
- 이벤트루프
- JPA
- 영속성 컨텍스트
- 게시판
- 정보처리기사
- sqld
- 깃허브
- Redis
- NoSQL
- SQL
- document database
- MongoDB
- 동적계획법
- 자바의 정석
- Spring Boot
- in-memory
- github
Archives
- Today
- Total
FreeHand
스트림1 본문
다양한 데이터 소스(컬렉션, 배열)를 표준화된 방법으로 다루기 위한 것.
스트림 사용법
- 스트림 생성
- 중간 연산(n번): 연산결과가 스트림
- 최종 연산(1번): 연산결과가 스트림이 아님(스트림의 요소를 소모함)
//예시
//스트림.중간연산1.중간연산2.중간연산3.최종연산
stream.distinct().limit(5).sorted().forEach(System.out::println)
스트림 특징
- 원본 데이터를 읽기만 가능하고 변경하지 않는다.(Read Only)
- 일회용이다. (필요하면 다시 스트림을 생성해야 한다.)
- 지연된 연산을 한다. (최종 연산 전까지 중간 연산이 수행되지 않는다.)
- 기본형 스트림(IntStream 등)을 제공하여 오토박싱&언박싱 비효율을 없앤다.
- 스트림 작업을 병렬로 처리할 수 있다.
스트림 생성
- 컬렉션 ⇨ 스트림
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> intStream = list.stream(); // 리스트를 스트림으로 변환
intStream.forEach(System.out::print); // 스트림의 모든 요소 출력 (끝나면 스트림이 닫힘)
- 배열 ⇨ 스트림
// 객체 배열 -> 스트림
Stream<String> strStream = Stream.of("a", "b", "c");
Stream<String> strStream = Stream.of(new String[] {"a", "b", "c"});
Stream<String> strStream = Arrays.stream(new String[] {"a", "b", "c"});
Stream<String> strStream = Arrays.stream(new String[] {"a", "b", "c"}, 0, 3); // 0~2번 인덱스까지
// 기본형 배열 -> 스트림
IntStream intStream = IntStream.of(1, 2, 3, 4);
IntStream intStream = IntStream.of(new int[] {1, 2, 3, 4});
IntStream intStream = Arrays.stream(new int[] {1, 2, 3, 4});
IntStream intStream = Arrays.stream(new int[] {1, 2, 3, 4}, 0, 3);
- 난수 스트림
// 무한 스트림
IntStream intStream = new Random().ints();
intStream.limit(5).forEach(System.out::println); // 무한 스트림은 limit으로 잘라서 사용
// 유한 스트림
IntStream intStream = new Random().ints(5); // 스트림 사이즈
IntStream intStream = new Random().ints(1, 10); // 난수의 범위
IntStream intStream = new Random().ints(5, 1, 10); // 사이즈 + 범위
- 특정 범위 값 스트림
IntStream intStream = IntStream.range(1, 5); // 1, 2, 3, 4
IntStream intStream = IntStream.rangeClosed(1, 5); // 1, 2, 3, 4, 5
- 람다식으로 스트림 생성
// iterate() 사용. 이전 요소를 seed로 사용해서 다음 요소를 계산
Stream<Integer> evenStream = Stream.iterate(0, n->n+2); // 무한 스트림
// generate() 사용. seed 없음
Stream<Double> randomStream = Stream.generate(Math::random); // 무한 스트림
//Stream<Double> randomStream = Stream.generate(()->Math.random());
- 파일로 스트림 생성
Stream<Path> Files.list(Path dir)
Stream<String> Files.lines(Path path)
- 빈 스트림
Stream emptyStream = Stream.empty();
'Language > Java' 카테고리의 다른 글
자바로 구현한 디자인 패턴 (0) | 2024.05.12 |
---|---|
병렬처리(Thread, Stream) (0) | 2024.02.19 |
함수형 인터페이스 (0) | 2024.01.07 |
익명 클래스 (0) | 2024.01.06 |
내부 클래스 (0) | 2024.01.06 |