gpt4 book ai didi

java - 迁移java 7到java 8 - forEach in forEach in forEach 并导致HashMap?

转载 作者:行者123 更新时间:2023-12-02 01:18:47 28 4
gpt4 key购买 nike

我的java7代码:

final Map<String, Method> result = new HashMap<>();
final Set<Class<?>> classes = getClasses(co.glue());

for (final Class<?> c : classes) {
final Method[] methods = c.getDeclaredMethods();
for (final Method method : methods) {
for (final Annotation stepAnnotation : method.getAnnotations()) {
if (stepAnnotation.annotationType().isAnnotationPresent(StepDefAnnotation.class)) {
result.put(stepAnnotation.toString(), method);
}
}
}
}
return result;

我尝试使用stream + flatMap + map + filter

result = classes.stream()
.flatMap(c-> c.getDeclaredMethods()
.stream())
.map(Annotation::getAnnotations)
.filter(...?????);

最佳答案

您可以使用 streamflatMap 来实现,如下所示:

 return classes.stream()
.flatMap(c -> Arrays.stream(c.getDeclaredMethods()))
.flatMap(m -> Arrays.stream(m.getAnnotations())
.filter(stepAnnotation -> stepAnnotation.annotationType().isAnnotationPresent(StepDefAnnotation.class))
.map(ann -> new AbstractMap.SimpleEntry<>(ann.toString(), m)))
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));

关于java - 迁移java 7到java 8 - forEach in forEach in forEach 并导致HashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58132257/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com