8. int Array -> Integer List 변환하기
2018. 7. 16. 16:08
1. Classic Example
Full example to convert a primitive Array to a List.
ArrayExample1.java
package com.mkyong.array;
import java.util.ArrayList;
import java.util.List;
public class ArrayExample1 {
public static void main(String[] args) {
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> list = convertIntArrayToList(number);
System.out.println("list : " + list);
}
private static List<Integer> convertIntArrayToList(int[] input) {
List<Integer> list = new ArrayList<>();
for (int i : input) {
list.add(i);
}
return list;
}
}
Output
list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note
You can’t use the popular
You can’t use the popular
Arrays.asList
to convert it directly, because boxing issue. int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// No, the return type is not what we want
List<int[]> ints = Arrays.asList(number);
2. Java 8 Stream
Full Java 8 stream example to convert a primitive Array to a List.
ArrayExample2.java
package com.mkyong.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ArrayExample2 {
public static void main(String[] args) {
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// IntStream.of or Arrays.stream, same output
//List<Integer> list = IntStream.of(number).boxed().collect(Collectors.toList());
List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());
System.out.println("list : " + list);
}
}
Output
list : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
References
'Get IT Note > Java' 카테고리의 다른 글
7. ASCII , UNICODE, UTF-8 (0) | 2018.07.05 |
---|---|
6. String, StringBuffer, StringBuilder 의 차이점 (0) | 2018.07.04 |
5. 불변객체와 가변객체 (0) | 2018.07.04 |
4. ArrayList와 Array간 변환 (0) | 2018.07.03 |
3. 예외처리 (0) | 2018.07.03 |