-
20221010 TIL Stream api와 친해진 하루TIL 2022. 10. 10. 16:12
저번 주부터 stream api를 배열과 함께 사용을 하다가 toArray()메소드가 Object[] 형태로 반환을 해서 형 변환에 어려움을 겪고 있었다.
캐스팅을 해도 아래와 같은 ClassCastException에러가 떠서 그냥 for문을 돌려서 오늘도 코딩테스트를 풀었다.
그런데 뭔가 방법이 있을 것 같아서 찾아보다가
Stream (Java Platform SE 8 )
A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream: int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight())
docs.oracle.com
에서 toArray안에 원하는 자료형을 자료형::new(array constructor reference)로 넣어주면 된다는 것을 찾았다.
toArray안에 array constructor reference를 넣어 줬더니 잘 작동하였다!
그런데 :: 연산자를 처음봐서 어떤 연산자인지 확인해보았다.
::연산자는 method reference operator라고 부르고, 메소드를 바로 클래스 옆에 바로 부르기 때문에 method reference operator라고 부른다.
<Class name>::<method name>
처럼 사용할 수 있다.
람다식과 작동방식은 동일한데, 인자를 써주지 않아서 더욱 깔끔한 표기법이다.
s-> System.out.println(s) //람다식 System.out::println //method reference
이 두 줄은 동일하게 작동한다.
ArrayType[]::new 는 생성자(new)에 대한 메소드 레퍼런스에 해당한다.
즉, 아래 두 개의 코드는 동일하게 작동한다.
toArray(size -> new int[size][]) toArray(int[][]::new)
toArray는 generator - a function which produces a new array of the desired type and the provided length 을 인자로 받기 때문에 array constructor reference를 넣어주면 잘 작동한다.
https://stackoverflow.com/questions/35914775/java-8-difference-between-method-reference-bound-receiver-and-unbound-receiver 어떻게 써야할 지 모르겠다면 메소드를 공식 문서에서 찾아보고 사용법을 익히자!
한 줄 요약: toArray메소드 안에 인자로 원하는 배열타입::new를 넣어주면 그 자료형으로 반환된다.'TIL' 카테고리의 다른 글
20221012 TIL SpyBean VS. MockBean (0) 2022.10.12 20221011 TIL 막힐 때는 단계를 나누어 차근차근 (0) 2022.10.11 20221009 TIL 쓰고 싶은 프로그램을 만들자 (0) 2022.10.09 20221008 TIL 그럴 수 있어. 이런 날도 있는 거지 뭐. (0) 2022.10.08 20221007 TIL 코테 기출 문제 분석하기 (1) 2022.10.07