| 리턴 타입 | 메서드 | 내용 |
|---|---|---|
| Object[] | toArray() | List의 모든 요소를 포함하는 배열 리턴 |
사용 예시
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
// 1
String[] str1 = list.toArray();
// 2
String[] str2 = list.toArray(new String[0]);
// 3
String[] str2 = list.toArray(new String[5]);
}
// 1
// 2
// 3
List를 기본 타입 배열로 변환
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
// 1
int[] int1 = new int[list.size()];
for(int i = 0; i<list.size(); i++){
int1[i] = list.get(i).intValue();
}
// 2
int[] int2 = list.stream()
.mapToInt(i -> i)
.toArray();
// 3
int[] int3 = list.stream()
.mapToInt(Integer::intValue)
.toArray();
// 4
int[] int4 = list.stream()
.filter(i -> i != null)
.mapToInt(i -> i)
.toArray();
}
// 1
// 2, 3
.mapToInt(i -> i) 자동으로 각 요소의 Integer 요소를 int형으로 언박싱 해준다..mapToInt(Integer::intValue) intValue 메서드를 통해 각 요소를 int형으로 변경해준다.// 4
.filter(i -> i != null) 를 추가하여 리스트의 null을 걸러내는 방법이다.