Loops 将嵌套循环更改为流

Loops 将嵌套循环更改为流,loops,lambda,java-8,java-stream,Loops,Lambda,Java 8,Java Stream,这是我的密码。我想使用streams和lambdas将其更改为Java8样式。你能帮我吗 Annotation[][] annotations = joinPoint.getTarget().getClass() .getMethod(methodName, signature.getParameterTypes()).getParameterAnnotations(); for (int i = 0; i < parametersCount; i++)

这是我的密码。我想使用streams和lambdas将其更改为Java8样式。你能帮我吗

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, "***************");
            }
        }
    }
Annotation[]annotations=joinPoint.getTarget().getClass()
.getMethod(methodName,signature.getParameterTypes()).getParameterAnnotations();
对于(int i=0;i
我不知道您想要实现什么,但将代码转换为
API如下所示:

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

你可以这样写:

// 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, "***********"));
请注意,由于以下原因,此问题不太适合流API:

  • 您正在修改现有的数据结构。当您在不可变的数据结构上操作(生成新的数据结构而不是改变现有的数据结构)时,流API是最有用的

  • 您有“并行”结构:
    args
    的第一个元素对应于
    注释的第一个元素,第二个元素也是如此,依此类推。这通常不是很好的代码设计,并且标准流API也没有定制来支持它


  • 为什么要更改它?arraylist与注释顺序连接我想了解这一点,但当我尝试时,在代码运行之前,args arraylist失败为空?如果是,如果在设置
    i-1
    th元素之前尝试设置第i个元素,则可能会出现异常。此外,您可能会多次覆盖同一i的args中的值。这就是你想要的吗?现在还不清楚您试图用这段代码实现什么。我尝试更改列表中与注释元素相关的元素