Stream의 mapToInt와 map

coh·2024년 10월 7일
0

JAVA

목록 보기
2/2

Stream은 수도꼭지다. 물을 똑똑 흘러내듯이 원소들을 똑똑 흘러낼 수 있는 API이다.

스트림을 사용하다가 문득 mapToInt와 map의 차이점이 뭔지 궁금해졌다.

결론부터 말하면 mapToInt와 map의 차이점은 스트림 처리에서 반환되는 타입이다.

mapToInt:정수형 스트림(IntStream)반환. 즉, 원소들이 int로 변환된다.
합계, 평균 연산을 스트림 중에 사용 가능함.

List<String> arr = List.of("1", "2", "3");

// int[]로 반환
int[] result = arr.stream()
	.mapToInt(Integer::parseInt)
    .toArray();

map: 객체형 스트림(Stream<T>) 반환. 즉, 원소들이 어떤 객체로 변환된다. 기본형(int) 대신 객체형(예를들어 Integer)로 반환된다.

List<String> arr = Arrays.asList("1", "2", "3")
List<Integer> result = arr.stream()
	.map(Integer::parseInt)
    .collect(Collectors.toList());

Array도 스트림을 사용할 수 있다.

String[] arr = line.split("");
Arrays.stream(arr).mapToInt(Integer::parseInt)
	.toArray();
profile
Written by coh

0개의 댓글