java 8:: 용법 (JDK 8 더 블 콜론 용법)

JDK 8 에는 이중 콜론 의 용법 이 있 습 니 다. 방법 을 매개 변수 로 stream 내부 에 전달 하여 stream 의 모든 요 소 를 이 방법 에 전달 하여 실행 하 는 것 입 니 다.
코드 는 사실 매우 간단 하 다.
이전 코드 는 일반적으로 다음 과 같 습 니 다:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public   class   AcceptMethod {        public   static   void    printValur(String str){          System.out.println( "print value : " +str);      }        public   static   void   main(String[] args) {          List al = Arrays.asList( "a" , "b" , "c" , "d" );          for   (String a: al) {              AcceptMethod.printValur(a);          }        // for each            al.forEach(x->{              AcceptMethod.printValur(x);          });      } }
현재 JDK 의 더 블 사칭 은:
1 2 3 4 5 6 7 8 9 10 11 12 13 public   class   MyTest {      public   static   void    printValur(String str){          System.out.println( "print value : " +str);      }        public   static   void   main(String[] args) {          List al = Arrays.asList( "a" "b" "c" "d" );          al.forEach(AcceptMethod::printValur);          //          Consumer methodParam = AcceptMethod::printValur;  //          al.forEach(x -> methodParam.accept(x)); // accept      } }
  
위의 모든 방법 으로 게임 을 수행 한 결 과 는 다음 과 같다.
1 2 3 4 print value : a print value : b print value : c print value : d
JDK 8 에 서 는 인터페이스 Iterable 8 에서 기본적으로 foreach 방법 을 실 현 했 고 JDK 8 에 추 가 된 인터페이스 Consumer 내 accept 방법 을 호출 하여 들 어 오 는 방법 파 라미 터 를 실 행 했 습 니 다.
JDK 소스 코드 는 다음 과 같 습 니 다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 /**       * Performs the given action for each element of the {@code Iterable}       * until all elements have been processed or the action throws an       * exception.  Unless otherwise specified by the implementing class,       * actions are performed in the order of iteration (if an iteration order       * is specified).  Exceptions thrown by the action are relayed to the       * caller.       *       * @implSpec       * The default implementation behaves as if:       *
{@code
      *     for (T t : this)       *         action.accept(t);       * }       *       * @param action The action to be performed for each element       * @throws NullPointerException if the specified action is null       * @since 1.8       */      default   void   forEach(Consumer  super   T> action) {          Objects.requireNonNull(action);          for   (T t :  this ) {              action.accept(t);          }      }
또한 JDK 8 이 변경 한 것 은 인터페이스 에서 기본 적 으로 실현 할 수 있 습 니 다. 바로 인터페이스 앞 에 default 을 추가 하여 이 인 터 페 이 스 를 실현 하 는 함수 가 기본 적 으로 실현 하 는 방법 에 대해 더 이상 실현 하지 않 아 도 됩 니 다.유사 한 것 은 static 방법 도 있다.현재 이 인 터 페 이 스 는 위 에서 언급 한 것 을 제외 하고 BiConsumer, BiFunction, Binary Operation 등 이 있 습 니 다. 자바 util. function 패키지 에 있 는 인 터 페 이 스 는 대부분 있 습 니 다. 접미사 가 Supplier 인 인 인 터 페 이 스 는 다른 소수 와 인터페이스 가 없습니다.

좋은 웹페이지 즐겨찾기