将Java7迁移到Java8-forEach中的forEach并生成HashMap?

将Java7迁移到Java8-forEach中的forEach并生成HashMap?,java,arrays,java-8,java-stream,Java,Arrays,Java 8,Java Stream,我的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

我的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
这样做:

 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));
returnclasses.stream()
.flatMap(c->array.stream(c.getDeclaredMethods()))
.flatMap(m->Arrays.stream(m.getAnnotations())
.filter(stepAnnotation->stepAnnotation.annotationType().isAnnotationPresent(StepDefAnnotation.class))
.map(ann->newAbstractMap.SimpleEntry(ann.toString(),m)))
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,AbstractMap.SimpleEntry::getValue));

您可以使用
平面地图
来完成它,例如:

 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));
returnclasses.stream()
.flatMap(c->array.stream(c.getDeclaredMethods()))
.flatMap(m->Arrays.stream(m.getAnnotations())
.filter(stepAnnotation->stepAnnotation.annotationType().isAnnotationPresent(StepDefAnnotation.class))
.map(ann->newAbstractMap.SimpleEntry(ann.toString(),m)))
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,AbstractMap.SimpleEntry::getValue));

@HadiJ请不要像这样使用
forEach
。要么正确使用流,要么坚持正常嵌套for循环。@marstran,同意@HadiJ请不要像这样使用
forEach
。要么正确使用流,要么坚持正常嵌套for循环。@marstran,同意!