2021年3月12日星期五

java stream: create pairs of child object by consuming pairs of parent object

I consume pairs of parent objects with lists:

public class Parent {    private List<Child> child;    private List<MixedChild> mixedChild;  }  public class Child {    private int id;    private int value;  }  public class MixedChild {    private Child jr;    private Child old;  }  

on startup I initialize only Child element (order of id isn't guaranteed),

 Parent parent1 = Parent.builder().child(List.of(      Child.builder().id(1).value(11).build(),      Child.builder().id(2).value(12).build(),      Child.builder().id(3).value(13).build(),      Child.builder().id(4).value(14).build()  )).build();  Parent parent2 = Parent.builder().child(List.of(      Child.builder().id(3).value(113).build(),      Child.builder().id(1).value(111).build(),      Child.builder().id(4).value(114).build(),      Child.builder().id(2).value(112).build()  )).build();  

output:

Parent(child=[Child(id=1, value=11), Child(id=2, value=12), Child(id=3, value=13), Child(id=4, value=14)], mixedChild=null)  Parent(child=[Child(id=3, value=113), Child(id=1, value=111), Child(id=4, value=114), Child(id=2, value=112)], mixedChild=null)  

And I need to consume this two parent elements to create list of MixedChild, for example

Stream mixedChildList = Stream.of(parent1, parent2).map( magicCode ).collect(Collectors.toList());  

rule of pairing is id=id, it means that result for first element must be

MixedChild(jr=Child(id=1, value=11), old=Child(id=1, value=111))  

Total: I need consume pair of parent objects and create list of MixedChild with rule id=id. This result will be written to one ot this parent objects , for example

parent1.setMixedChild(resultOfStream);  
https://stackoverflow.com/questions/66607023/java-stream-create-pairs-of-child-object-by-consuming-pairs-of-parent-object March 13, 2021 at 04:48AM

没有评论:

发表评论