【问题标题】:migration java 7 to java 8 - forEach in forEach in forEach and result in HashMap?将java 7迁移到java 8 - forEach中的forEach中的forEach并导致HashMap?
【发布时间】:2020-01-27 15:28:39
【问题描述】:

我的 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(...?????);

【问题讨论】:

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

标签: java arrays java-8 java-stream


【解决方案1】:

您可以使用 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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 2022-06-18
    相关资源
    最近更新 更多