Home [Java] Stream 문법
Post
Cancel

[Java] Stream 문법

코딩테스트 문제를 풀다가 자료형 변환하는 방법 중 stream에 대해 정리하게 되었습니다.

1️⃣ Stream이란?

  • Java 8부터 도입된 기능
  • 배열이나 리스트 같은 데이터들을 선언형(데이터 중심 방식)으로 처리
  • for나 if 없이 .map(), .filter(), .collect() 등을 사용해 가공 가능

자주 쓰는 Stream 메서드

메서드설명
filter()조건에 맞는 요소만 남김
map()각 요소를 변형함
mapToInt()요소를 int로 변환
boxed()primitive → 객체형 (예: int → Integer)
collect()최종 결과를 리스트 등으로 수집
forEach()요소 하나씩 반복 수행
sorted()정렬
distinct()중복 제거

2️⃣ 자료형 변환 예시

Integer[] → int[]

1
2
3
4
Integer[] boxedArray = {1, 2, 3, 4};
int[] unboxedArray = Arrays.stream(boxedArray)
                           .mapToInt(Integer::intValue)
                           .toArray();

int[] → Integer[]

1
2
3
4
int[] primitiveArray = {1, 2, 3, 4};
Integer[] boxedArray = Arrays.stream(primitiveArray)
                             .boxed()
                             .toArray(Integer[]::new);

List → int[]

1
2
3
4
5
6
7
8
9
10
11
12
13
List<Integer> list = Arrays.asList(1, 2, 3);
int[] arr = list.stream()
                .mapToInt(Integer::intValue)  // i -> i.intValue() 축약 표현
                .toArray();

int[] arr2 = list.stream()
                .mapToInt(i -> i)  // 내부적으로 unboxing 자동 수행
                .toArray();

// 반복문 사용
int[] arr1 = new int[list.size()]
for (int i = 0; i < list.size(); i++)
    arr1[i] = list.get(i).intValue();

int[] → List

1
2
3
4
int[] arr = {1, 2, 3};
List<Integer> list = Arrays.stream(arr)
                           .boxed()
                           .collect(Collectors.toList());

String → List

1
2
3
4
String str = "hello";
List<Character> charList = str.chars()
                              .mapToObj(c -> (char) c)
                              .collect(Collectors.toList());

String → List

1
2
3
String str = "a,b,c";
List<String> list = Arrays.stream(str.split(","))
                          .collect(Collectors.toList());

String → Character[]

1
2
3
4
5
String str = "abcdefg";
Character[] charArr = str.chars()
                         .mapToObj(c -> (char) c)
                         .toArray(Character[]::new);
System.out.println(Arrays.toString(charArr));  // [a, b, c, d, e, f, g]

String → String[]

1
2
3
4
5
6
String str = "a,b,c,d,e,f,g";
String[] strArr = str.chars()
                     .filter(c -> c != ',')
                     .mapToObj(c -> String.valueOf((char) c))
                     .toArray(String[]::new);
System.out.println(Arrays.toString(strArr));  // [a, b, c, d, e, f, g]

String[] → String

1
2
3
4
5
String[] arr = {"a", "b", "c"};
String result = String.join(",", arr);  // "a,b,c"

String result = Arrays.stream(arr)
                      .collect(Collectors.joining(","));

3️⃣ 기타 활용법

문자열 안에서 숫자만 추출하기

1
2
3
4
5
6
String s = "a1b2c3";
List<Integer> digits = s.chars()
                        .filter(Character::isDigit)
                        .map(c -> c - '0')
                        .boxed()
                        .collect(Collectors.toList());
This post is licensed under CC BY 4.0 by the author.