Java
[Java] 주어진 배열에서 특정 값을 갖는 index 찾기 (stream) (참조글 읽어보기)
noogu
2022. 3. 8. 11:32
g라는 int형 배열에서 g[idx] 값이 0인 idx 를 "루트노드" 라고 하고, 이 루트노드를 찾는 상황이라고 가정.
이제까지 for문을 사용해 탐색해왔는데 요즘도 이렇게 하나? 라는 생각이 들었다.
python에서 range 사용하는 것 처럼 할 수는 없을까? stream에 있을 것 같은데..라고 생각하며 찾아보았다.
IntStream 이라는 것은 처음 사용해보았다.
public static int findRoot(int[] g){
return IntStream.range(0, g.length)
.filter(i -> g[i] == 0)
.findAny().getAsInt();
}
물론 findAny() 는 Optional을 리턴하기 때문에 Optional로 리턴하게 하여, null인 경우에 대한 예외처리는 리턴 받는 쪽에서 해주는게 좋을 듯 하다.
https://www.developer.com/project-management/stream-operations-supported-by-the-java-streams-api/
Stream Operations Supported by the Java Streams API | Developer.com
Stream APIs is one of the most sophisticated implementations in Java. Stream APIs are mainly used in association with the collection framework. Sometimes,
www.developer.com