Java/Grammar

[Java 문법] Stream API 주요 method 정리

annovation 2024. 12. 31. 08:47

Stream API

기존 게시글 참조 !

https://annovation.tistory.com/21

 

[Java 문법] Stream API

Stream APIJava Stream은 Java 8에서 도입된 기능으로, 데이터를 선언적이고 효율적으로 처리할 수 있는 도구입니다.기존의 반복문(for, while)을 사용한 명령형 방식과 달리, Stream은 함수형 프로그래밍

annovation.tistory.com


구성 요소 별 주요 메서드

 

1. 중간 연산 (Intermediate Operations)

메서드 설명 예제
filter() 조건에 맞는 요소만 필터링 filter(n -> n > 5)
map() 각 요소를 변환 map(n -> n * 2)
sorted() 요소를 정렬 (기본 오름차순 또는 Comparator 사용) sorted(Comparator.reverseOrder())
distinct() 중복 요소 제거 distinct()
limit() 결과를 지정된 개수만큼 제한 limit(3)
skip() 처음 몇 개의 요소를 건너뜀 skip(2)
flatMap() 각 요소를 Stream으로 변환하고 병합 flatMap(Collection::stream)

 

* 예제

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Alice");

names.stream()
    .distinct() // 중복 제거
    .sorted()   // 정렬
    .forEach(System.out::println); // 출력

 

➡️ 출력

Alice
Bob
Charlie

 

 

2. 최종 연산 (Terminal Operations)

메서드 설명 예시
forEach() 각 요소를 소비 (출력, 저장 등) forEach(System.out::println)
collect() 데이터를 리스트, 맵, 집합 등으로 변환 collect(Collectors.toList())
reduce() 요소를 하나로 결합 reduce((a, b) -> a + b)
count() 요소 개수를 반환 count()
anyMatch() 조건에 맞는 요소가 하나라도 있는지 확인 anyMatch(n -> n > 5)
allMatch() 모든 요소가 조건을 만족하는지 확인 allMatch(n -> n > 0)
noneMatch() 모든 요소가 조건을 만족하지 않는지 확인 noneMatch(n -> n < 0)
findFirst() 첫 번째 요소를 반환 findFirst()
findAny() 임의의 요소를 반환 (병렬 스트림에서 유용) findAny()

 

* 예제

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

long count = numbers.stream()
        .filter(n -> n % 2 == 0) // 짝수만 필터링
        .count(); // 개수 계산

System.out.println("짝수 개수: " + count); // 출력: 짝수 개수: 2

출처

OpenAI ChatGPT (https://openai.com)

 

 

'Java > Grammar' 카테고리의 다른 글

[Java 문법] StringBuilder  (0) 2025.01.10
[Java 문법] map.forEach()  (1) 2025.01.05
[Java 문법] 데이터 타입 (Data Type)  (1) 2024.12.28
[Java 문법] 롬복 (Lombok)  (1) 2024.12.22
[Java 문법] HashMap  (1) 2024.12.10