I have a requirement related to Streams in Java. I need to iterate over a List of Objects,where each object has Integer property and a List property.
What I need is, if same objects has the same ID, I need to concat the lists. Let me illustrate the example with a little bit of a simple code:
Here just defining 2 simple classes:
public static class Wrapper {
Integer id ;
List<Element> list;
public Wrapper(Integer id, List<Element> list) {
this.id = id;
this.list = list;
}
}
public static class Element {
String content ;
public Element(String content) {
this.content = content;
}
}
Now in a Main Java method,creating same objects for the porpuse of the example:
List<Wrapper> list=new ArrayList();
ArrayList<Element> listForWrapper1= new ArrayList();
listForWrapper1.add(new Element("Content A"));
listForWrapper1.add(new Element("Content B"));
ArrayList<Element> listForWrapper2= new ArrayList();
listForWrapper2.add(new Element("Content C"));
listForWrapper2.add(new Element("Content D"));
ArrayList<Element> listForWrapper3= new ArrayList();
listForWrapper3.add(new Element("Content E"));
listForWrapper3.add(new Element("Content F"));
Wrapper wrapper1=new Wrapper(1,listForWrapper1);
Wrapper wrapper2=new Wrapper(2,listForWrapper2);
//Here this Wrapper has the same ID than wrapper2
Wrapper wrapper3=new Wrapper(2,listForWrapper3);
//Adding Elements to List
list.add(wrapper1);
list.add(wrapper2);
list.add(wrapper3);
As you can see, I am adding 3 Wrappers to the list, BUT 2 of them have the same ID
What I want is when Wrapper IDs are the same in the array,just merge both list. So in this example the result should be:
A list with 2 Element:
Element 1 : Wrapper Object with ID 1,with 2 Elements inside its list property,Element Content A ,and Element Content B
Element 2: Wrapper Object with ID 2,with 4 Elements inside its list property,Element Content C,Element Content D,Element Content E and Element Content F.
How can I achieve this result using Streams? I cant think any elegant solution!
Thanks in advance!
List<Wrapper> combinedList=list.stream().....