java-8 - 在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;
}
解决方案
您必须打开一个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 + "|");
}
});
推荐阅读
- python - Tensorflow / keras multi_gpu_model 不拆分为多个 gpu
- android - 应用程序有时会因“不允许后台启动:服务意图”而崩溃
- javascript - 使用 moment.js 将小时 UTC 转换为本地
- mongodb - 不同的过时版本生活在地窖里
- python-3.x - 从轮廓中查找局部最大值点 OPENCV PYTHON
- haskell - Haskell Cookbook,Monoid 实例
- python - 负 int 输入的最大值和最小值
- r - Formatstyle R 数据表
- javascript - Meteor:如何将用户集合中的用户名添加到我创建的新集合中?
- python - 从 seaborn.heatmap 中的图中删除蒙面项目