본문 바로가기
Today I Learned/Java

[Java] Integer 타입 ArrayList를 int 타입 배열로 변환

by 프로그래 밍구 2023. 10. 26.

주저리주저리

 코딩테스트 연습 중 int형 배열을 정답으로 반환해야 하는 상황. 필자는 매번 Integer 타입의 ArrayList를 반환하여 'cannot be converted to int'라는 오류를 만난다. 그만 까먹고 싶어서 기록한다.

 

본론

List<Integer> list = new ArrayList<>();
    
list.add(1);
list.add(2);

int[] arr = list.stream()
    	.mapToInt(i -> i)
        .toArray();

 

 Integer타입 ArrayList를 선언하고 데이터를 삽입한다. 그 이후 list를 stream으로 변환한 후 mapToInttoArray()를 이용하여 int형 배열로 만든다.

댓글