boxed()

혜연·2025년 2월 27일
0

Java

목록 보기
4/6
post-thumbnail

boxed()란❓

: 자바의 Stream API에서 기본형 스트림(int,double)을 래퍼 클래스로 변환하는 메서드
ex) int -> Integer, double -> Double

  • IntStream, DoubleStream 과 같은 기본형 스트림을 Stream, Stream 같은 객체 스트림으로 변환
    나는 주로 기본형 배열을 리스트로 바꿀때 사용한다.

📌예제

 import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class test {
    public static void main(String[] args) {

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

    }
}
 

Arrays.stream(arr)은 IntStream을 반환한다. IntStream 상태에서는 List로 반환할 수 없기에 boxed()를 통해 Stream 형태로 변환한다.
Stream에서는 collect(Collectors.toList()) 가 사용 가능하기에 List을 반환할 수 있다.

  • 기본형 스트림은 collect() 메서드를 사용할 수 없다. 왜❓
    collect()는 객체 스트림에서만 제공되는 메서드이기 때문이다.

📌 리스트에서 기본형 배열 (List -> int[])

반대로 가는법

int [] arr = list.stream()
  				  .mapToInt((i) -> i.intValue())
  				 .toArray();
  • intValue() 메서드를 사용해서 Integer 형을 int로 변환할 수 있다.

0개의 댓글

관련 채용 정보