본문 바로가기

Algorithm/Programmers

Level 1: 나누어 떨어지는 숫자 배열, Stream의 filter()와 sorted()

더보기

int[]의 Element 중 int(divisor)로 나누어 떨어지는 값오름차순으로 정렬한 배열을 반환합니다.

문제 풀이: Stream의 filter와 sorted 사용

입력된 int[]를 Stream으로 필터합니다. 필터 결과는 sorted()를 사용해 오름차순으로 정렬합니다.

import java.util.*;

public class Solution {
	public int[] solution(int[] arr, int divisor) {
		int[] res = Arrays.stream(arr).filter(i -> (0 == i % divisor)).sorted().toArray();
		return (res.length == 0) ? new int[] { -1 } : res;
	}
}
코드 비고
Line 5 filter int[]를 Stream으로 filter합니다.
divisor로 정확히 나누어 떨어지는 값만 필터합니다.
sorted 필터된 결과를 오름차순으로 정렬합니다.

오름차순 정렬은 Arrays.sort()로 대체 할 수 있습니다.

import java.util.*;

public class Solution {
	public int[] solution(int[] arr, int divisor) {
		int[] res = Arrays.stream(arr).filter(i -> (0 == i % divisor)).toArray();
		Arrays.sort(res);
		return (res.length == 0) ? new int[] { -1 } : res;
	}
}