user08152017:
Eu tenho um teste de classe
public class Test{
String codes;
String field 1;
....
String field n;
}
Eu tenho uma lista de objetos de teste
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", ...)
Tentando converter esta list1
a nova list2
a cada código de A, B, C ... para seu próprio objeto, retendo os campos restantes.
List<Test>
testObj1("A", ....)
testObj2("B", ....)
testObj3("C", ....)
list1.stream().collect(Collectors.toList())
Eu consegui isso usando loops (código Sudo), mas procurando uma melhor lógica
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
}
}
também:
Você pode usar Stream.map
com flatMap
como:
List<Test> finalList = list1.stream()
.flatMap(e -> Arrays.stream(e.getCodes().split(","))
.map(c -> new Test(c, e.getField1(), e.getFieldn())))
.collect(Collectors.toList());
Isso pressupõe que a sua Test
classe teria um construtor semelhante à seguinte aplicação:
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
}