String 타입의 List를 배열로 변환할 때는 toArray()를 사용하면 변환 가능.
하지만 Integer형은 toArray()로 바로 안되서 int로 바꾸고 toArray() 적용
public static void main(String args[]) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
//1)
int[] arr3 = list.stream()
.mapToInt(Integer::intValue)
.toArray();
// 2)
int[] arr2 = list.stream()
.mapToInt(i -> i)
.toArray();
// 3)
int[] arr1 = new int[list.size()]
for (int i = 0 ; i < list.size() ; i++)
arr1[i] = list.get(i).intValue();
}
1) 리스트를 스트림으로 변환 후, map을 이용해서 intValue 메서드를 통해 각 요소를 int형으로 변경, toArray().
2) 리스트를 스트림으로 변환 후, map을 이용해서 자바가 자동으로 각 요소의 Integer 요소를 int형으로 unbox, toArray(). (java 5 이상)
3) 반복문. 기본적인 방법. intValue 메서드를 사용해여 int형으로 만든 후 배열에 삽입.
'코테 공부 > java' 카테고리의 다른 글
boolean 변수 초기화? (0) | 2023.05.06 |
---|---|
Integer.toBinaryString(i)-이진문자열, stream.filter(람다식)-이렇게도 활용. 범위 내 0,5로만 이루어진 모든 정수 배열 문제. (0) | 2023.05.06 |
IntStream, LongStream 의 메서드 range(시작 포함, 끝 불포함) rangeClosed(시작 포함, 끝 포함) (0) | 2023.05.04 |
ArrayList 초기화 (0) | 2023.05.04 |
Collections.max(컬렉션 객체명) .min(컬렉션 객체명) (0) | 2023.05.03 |