我有一个课程测试
public class Test{
String codes;
String field 1;
....
String field n;
}
我有一个测试对象列表
List<Test> objects,code can be one or more with a comma separated
testObj1("A","field1".."fieldn")
testObj2("B,C",...)
testObj3("D,E,F",....)
testObj4("G",...)
通过保留其余字段,尝试将每个代码A,B,C …将此list1转换为新的list2,并将其转换为自己的对象.
List<Test>
testObj1("A",....)
testObj2("B",....)
testObj3("C",....)
list1.stream().collect(Collectors.toList())
我使用循环(Sudo代码)实现了这一点,但是正在寻找更好的逻辑
for(loop thru list1){
String[] codesArr = testObj1.codes.split(",");
for (String code : codesArr) {
//Create new Obj
Test obj = new Test(code,testObj1.copyotherfields);
//Add obj to list2
}
}
最佳答案
您可以将Stream.map与flatMap一起使用:
List<Test> finalList = list1.stream()
.flatMap(e -> Arrays.stream(e.getCodes().split(","))
.map(c -> new Test(c,e.getField1(),e.getFieldn())))
.collect(Collectors.toList());
假设您的Test类将具有类似于以下实现的构造函数:
class Test {
String codes;
String field1;
String fieldn;
// would vary with the number of 'field's
Test(String codes,String field1,String fieldn) {
this.codes = codes;
this.field1 = field1;
this.fieldn = fieldn;
}
// getters and setters
}