java - 迁移 java 7 到 java 8 - 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
result = classes.stream()
.flatMap(c-> c.getDeclaredMethods()
.stream())
.map(Annotation::getAnnotations)
.filter(...?????);
解决方案
你可以这样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));
推荐阅读
- java - 将布局绑定到屏幕分辨率
- javascript - 尽管使用了useEffect,但反应状态却落后了一步
- c# - 在 Xamarin 中打开或关闭位置/或查看位置设置
- angular - 如何对使用服务进行 GET 调用的 Angular 组件进行单元测试
- r - 你如何计算随机生成的数据帧的比例?
- c# - 在 Xamarin 中播放 .wav 音频
- javascript - 在 nodejs 中的 Square API 中格式化来自 webhook 的响应
- docker - 如何让管理员使用 Docker 在本地运行
- android - 如何获取 AdView 横幅高度
- javascript - 正确位于 Json 中的 Filterring 数组