2016-08-03 28 views
-1

這是我的代碼。我想使用流和lambdas將其更改爲Java 8樣式。你可以幫幫我嗎?將嵌套循環更改爲流

Annotation[][] annotations = joinPoint.getTarget().getClass() 
      .getMethod(methodName, signature.getParameterTypes()).getParameterAnnotations(); 

    for (int i = 0; i < parametersCount; i++) { 
     for (int j = 0; j < annotations[i].length; j++) { 
      Annotation annnotation = annotations[i][j]; 
      if (annnotation.annotationType().isAssignableFrom(Hidden.class)) { 
       args.set(i, "***************"); 
      } 
     } 
    } 
+0

什麼是'args'? – Eran

+0

你爲什麼要改變它? – Andrew

+0

arraylist與註釋順序連接 – lassa

回答

0

我不知道你想實現什麼,但你的代碼來Stream API的過渡看起來是這樣的:

IntStream.range(0, parametersCount).forEach(
    i -> Arrays.stream(annotations[i]) 
       .filter(a -> a.annotationType().isAssignableFrom(Hidden.class)) 
       .forEach(annotation -> args.set(i, "***********")) 
); 
0

您可以編寫以下方法:

// create stream of indices 
IntStream.range(0, parametersCount) 
     // filter it leaving only those which have at least one Hidden annotation 
     .filter(i -> Stream.of(annotations[i]) 
       .anyMatch(a -> a.annotationType().isAssignableFrom(Hidden.class))) 
     // reset the corresponding args 
     .forEach(i -> args.set(i, "***********")); 

請注意,由於以下原因,此問題不太適合Stream API:

  1. 您正在修改現有的數據結構。當你操作不可變的數據結構(產生新東西而不是改變現有的東西)時,Stream API是最有用的。

  2. 您有「並行」結構:args的第一個元素對應於annotations的第一個元素,第二個元素也是如此。這通常不是很好的代碼設計,並且標準的Stream API不適合支持它。