Java 7到Java 8的迁移-forEach中的forEach中的forEach并导致HashMap? [英] migration java 7 to java 8 - forEach in forEach in forEach and result in HashMap?
本文介绍了Java 7到Java 8的迁移-forEach中的forEach中的forEach并导致HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的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
I try with stream
+ flatMap
+ map
+ filter
result = classes.stream()
.flatMap(c-> c.getDeclaredMethods()
.stream())
.map(Annotation::getAnnotations)
.filter(...?????);
推荐答案
您可以使用 stream
和 flatMap
这样来实现:
You can do it with stream
and flatMap
like:
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 7到Java 8的迁移-forEach中的forEach中的forEach并导致HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文