Converting Java List to another using java streams

user08152017 :

I have a class Test

public class Test{
  String codes;
  String field 1;
  ....
  String field n;
}

I have a list of test objects

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", ...)

Trying to convert this list1 to new list2 with each code A, B, C... to its own object by retaining the remaining fields.

List<Test>
testObj1("A", ....)
testObj2("B", ....)
testObj3("C", ....)

list1.stream().collect(Collectors.toList())

I achieved this using loops (Sudo code) but looking for better logic

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
  }
}
Naman :

You can use Stream.map with flatMap as :

List<Test> finalList = list1.stream()
        .flatMap(e -> Arrays.stream(e.getCodes().split(","))
                .map(c -> new Test(c, e.getField1(), e.getFieldn())))
        .collect(Collectors.toList());

This assumes that your Test class would have a constructor similar to the following implementation:

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
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102051&siteId=1