首页 > 解决方案 > 在java 8中转换基于for循环的索引

问题描述

是否可以将下面给出的 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;
}

标签: java-8

解决方案


您必须打开一个InsStream迭代args索引,然后创建一个与其对应SimpleEntry的每个索引(根据您的代码),然后您可以应用您的业务逻辑。argannotaton

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 + "|");
          }
        });

推荐阅读