문제 : 정수가 들어있는 배열 num_list가 매개변수로 주어집니다. num_list의 원소의 순서를 거꾸로 뒤집은 배열을 return하도록 solution함수를 완성해주세요.
해답 및 해설 :
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;
class Solution {
public int[] solution(int[] numList) {
List<Integer> list = Arrays.stream(numList).boxed().collect(Collectors.toList());
Collections.reverse(list);
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
Arrays.stream을 이용하여 int배열을 intStream으로 변환한다. 그리고 boxed를 이용하여 intStream -> integer객체의 stream으로 변환, collcet() 를 이용하여 List<integer>로 변환한다.
그리고 Collections.reverse를 사용하여 list를 역순으로 뒤집는다. 반환값으로 List<integer>를 stream으로 변환하고 mapToint로 각 integer를 int로 mapping한 후, toArray()로 int배열로 최종적으로 만든다!
<알아두어야할 개념>
boxed() : stream 중 한 개념, IntStream -> Stream<Integer> 전환해준다.
Collections.reverse(배열) : 역순으로 정렬(sort 먼저 사용시, 내림차순 정렬)<-> Collections.sort(배열) (오름차순)
.mapToInt() : 스트림을 IntStream으로 변환해주는 메서드
inValue : integer객체에서 int형 값을 뽑아내는 메서드
'코딩 테스트' 카테고리의 다른 글
[java] 피자 나눠먹기(3) - Math.ceil (0) | 2024.02.18 |
---|---|
[java] 편지 (0) | 2024.02.11 |
[JAVA] 부분 문자열 - .contains() (0) | 2024.01.17 |
[java] 정수의 제곱근 판별 (Math.sqrt, Math.pow) (0) | 2024.01.12 |
[java] x만큼 간격이 있는 n개의 숫자 (0) | 2024.01.08 |