문제
내가 작성한 정답
class Solution {
public int[] solution(int[] array) {
int a = array[0];
int b = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] > a ) {
a = array[i];
b = i;
}
}
int[] answer = {a,b};
return answer;
}
}
다른 사람들이 작성한 정답
StreamAPI
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public int[] solution(int[] array) {
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
int max = list.stream().max(Integer::compareTo).orElse(0);
int index = list.indexOf(max);
return new int[] {max, index};
}
}
StreamAPI을 사용할 수 있는 형식
- 컬렉션 - stream() 메서드를 사용하여 스트림으로 변환. : List: ArrayList, LinkedList 등 Set: HashSet, TreeSet 등 Queue: LinkedList, PriorityQueue 등
- 배열 - Arrays.stream(array) 메서드를 사용하여 스트림으로 변환.
- 파일 - Files.lines(Path path)를 사용하여 파일의 각 줄을 스트림으로 읽을 수 있다.
- 정수 범위 - IntStream.range(int startInclusive, int endExclusive)와 같은 메서드를 사용하여 특정 범위의 정수로 스트림을 생성할 수 있다.
- Stream.of(): Stream.of(T... values)를 사용하여 여러 개의 값을 직접 스트림으로 만들 수 있다.
Share article