Java Converting Arrays to Lists

Byul·2023년 6월 13일

Java

목록 보기
3/10

String[] -> List<String>

String[] stringArray = { "Byul", "Deep" };
List<String> stringList = null;
// with Arrays.asList()
stringList = Arrays.asList(stringArray); // immutable
// with List.of()
stringList = List.of(stringArray); // immutable 
stringList = new ArrayList<>(stringList); // mutable

int[] -> List<Integer>

int[] intArray = { 3, 1, -1 };
List<Integer> intList = null;
// with Arrays.asList()
intList = Arrays.asList(Arrays.stream(intArray).boxed().toArray(Integer[]::new)); // immutable
// with List.of()
intList = List.of(Arrays.stream(intArray).boxed().toArray(Integer[]::new)); // immutable
intList = new ArrayList<>(intList); 
// with IntStream ** shortest and mutable! **
intList = IntStream.of(intArray).boxed().collect(Collectors.toList()); // mutable
profile
junior backend developer

0개의 댓글