我有两个POJO, 下面的示例代码
class A {
String name;
Object entries; // this can be a List<String> or a string - hence Object datatype
//getters and setter here
}
class B {
int snumber;
List<A> values;
//getters and setters here
}
控制器类
class ControllerA {
public getList(B b) {
List<String> list = b.getValues().stream.map(e -> e.getEntries()).collect(Collectors.toList()));
}
}
这会返回一个列表清单:
[[12345, 09876], [567890, 43215]]
但我想要的是像
这样的单一列表[12345,09876,567890, 43215]
如何使用Java 8流做到这一点?
我也尝试了flatMap
,但这与条目的Object
数据类型不相符。
答案 0 :(得分:3)
将List<String>
视为entries
类中的字段A
。
评论中提到@Eugene,
如果是单个String,则将其设为单个元素的
List
;如果它是多个字符串的列表就是这样的。
使用单一类型的集合可以简化流程:
b.getValues() // -> List<A>
.stream() // -> Stream<A>
.map(A::getEntries) // -> Stream<List<String>>
.flatMap(Collection::stream) // -> Stream<String>
.collect(Collectors.toList()); // -> List<String>