在Java 8中基于索引的索引进行循环

时间:2019-02-21 06:59:12

标签: java-8

是否可以将下面给定的for循环转换为Java 8代码?

 Object[] args = pjp.getArgs();
    MethodSignature methodSignature = (MethodSignature) pjp.getStaticPart()
            .getSignature();
    Method method = methodSignature.getMethod();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    StringBuilder methodArgs = new StringBuilder();
    for (int argIndex = 0; argIndex < args.length; argIndex++) {
        for (Annotation annotation : parameterAnnotations[argIndex]) {
            if ((annotation instanceof RequestParam) || (annotation instanceof PathVariable) || (annotation instanceof RequestHeader)) {
                methodArgs.append(args[argIndex] + "|");
            } else if ((annotation instanceof RequestBody)) {
                methodArgs.append(mapper.writeValueAsString(args[argIndex]) + "|");
            }
        }
    }

我尝试使用下面给出的Java 8代码。函数名称是随机获取的

public void some() {
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    Arrays.stream(parameterAnnotations)
            .map(f -> asd(f));
}

private Object asd(Annotation[] annotations) {
    Arrays.stream(annotations)
            .map(a -> change(a)); //here is problem...how i can access args[argIndex]
    return null;
}

1 个答案:

答案 0 :(得分:1)

您必须打开一个InsStream以遍历args索引,然后为每个SimpleEntry创建一个arg,并与之对应的annotaton(根据您的代码),然后您可以应用业务逻辑。

IntStream.range(0, args.length)
        .mapToObj(argIndex -> new AbstractMap.SimpleEntry<>(args[argIndex], parameterAnnotations[argIndex]))
        .flatMap(objectSimpleEntry -> Arrays.stream(objectSimpleEntry.getValue()).map(annotation -> new AbstractMap.SimpleEntry<>(objectSimpleEntry.getKey(), annotation)))
        .forEach(objectAnnotationSimpleEntry -> {
          Annotation annotation = objectAnnotationSimpleEntry.getValue();
          Object arg = objectAnnotationSimpleEntry.getKey();
          if ((annotation instanceof RequestParam) || (annotation instanceof PathVariable) || (annotation instanceof RequestHeader)) {
            methodArgs.append(arg + "|");
          } else if ((annotation instanceof RequestBody)) {
            methodArgs.append(arg + "|");
          }
        });