【发布时间】:2015-03-11 13:54:57
【问题描述】:
用例
我正在使用第 3 方库,其中有两个非常相似的类没有实现接口。该代码当前循环遍历项目列表以使用这些类中的一个来查找对象的第一次出现,然后将其转换为处理它的流。如果我可以将此代码转换为使用流并将其链接到我的其余代码,那就太好了。
当前代码
for (Component3Choice component: components) {
if (component instanceof OptionalComponent3Bean) {
OptionalComponent3Bean section = (OptionalComponent3Bean) component;
entryStream = section.getSection().getEntry().stream()
break;
}
else if (component instanceof RequiredComponent3Bean) {
RequiredComponent3Bean section = (RequiredComponent3Bean) component;
entryStream = section.getSection().getEntry().stream();
break;
}
}
... do something with the stream ...
所需代码
components.stream()
.filter(entry -> entry instanceof OptionalComponent3Bean
|| entry instanceof RequiredComponent3Bean)
.findFirst()
.map( {{ cast entry }} )
.map( castedEntry.getSection().getEntry())
... continue on with my processing
问题
是否可以根据流中的前一个过滤器转换条目?
【问题讨论】:
-
Component3Choice定义了一个方法getSection()吗? -
你能修改
OptionalComponent3Bean和RequiredComponent3Bean来实现一个定义getSection()的接口(例如HasSection)吗? -
不幸的是,我无权访问该库的源代码。 :(
标签: java java-8 java-stream