느꼈던 불편함에 대하여
코딩을 하다 보면 배열을 동적으로 관리해야 하는 상황이 자주 생긴다. 처음에는 배열을 다루기 위해 for문을 반복해서 돌리며 값을 옮기거나 추가하는 방식을 사용했다. 하지만 이런 방식은 코드가 길어지고 유지보수도 쉽지 않았다. 그러던 중, 배열을 List로 변환한 뒤 관리하는 것이 훨씬 유연하다는 걸 깨달았다. 특히 람다식(Stream)을 활용하면 반복문 없이도 가독성 좋은 코드로 깔끔하게 변환할 수 있어 큰 도움이 되었다.
int[] -> List<Integer> 변환
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] testArr = {1, 2, 3, 4, 5};
List<Integer> newList = Arrays.stream(testArr)
.boxed()
.collect(Collectors.toList()); // JDK 16 이상일 경우 .toList()를 사용가능
System.out.println(newList); // [1, 2, 3, 4, 5]
}
}
- Arrays.stream(testArr) -> 기본형 int[]를 intStream으로 변환
- boxed()를 사용하여 int -> Integer로 객체로 하나씩 포장함
- collect(Collectors.toList()) -> 스트림을 리스트로 모음
⭐️중요) collect(Collectors.toList()) 와 toList()에 대하여
단순히 toList()처럼 간단히 변환하는 방법을 사용할 때, 그 뒤에 숨겨진 중요한 특징을 이해하지 못하면 예상치 못한 버그나 제한에 부딪힐 수 있다. toList()는 불변 리스트이기 때문이다.
불변 리스트란?
- 리스트에 원소를 추가, 삭제, 변경할 수 없는 리스트임
그럼 이러한 이유에도 불변 리스트를 사용하는 이유는?
- 여러 메서드나 스레드에서 공유되는 리스트가 의도치 않게 변경되는 것을 막아줌
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] testArr = {1, 2, 3, 4, 5};
List<Integer> newList = Arrays.stream(testArr)
.boxed()
.toList();
newList.add(6); // Exception in thread "main" java.lang.UnsupportedOperationException
System.out.println(newList);
}
}

List<Integer> -> int[] 변환
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
int[] arr = list.stream().mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(arr)); // [1, 2, 3, 4, 5]
}
}
- stream()
- mapToInt() -> Integer를 int로 변환
- toArray() -> int[] 로 완성
'Java' 카테고리의 다른 글
| 오름차순 정렬과 내림차순 정렬에 대해 알아보자 (0) | 2025.12.05 |
|---|---|
| ArrayList가 처음이라면 꼭 알아야 할 핵심 기능 (0) | 2025.12.04 |
| 새벽 코딩하다가 알게 된 String.repeat() - 반복문 대신 이렇게 쓰자! (0) | 2025.12.04 |
