I have two classes that look like:
public class A {
String a;
String b;
String v;
List<Pmt> pmtList;
}
public class Pmt {
String id;
String b;
List<Transaction> trList;
}
How to transform to create a new payment list that can replace current payment list ( pmtList
) such that each payment object has only one Transaction
each using Java?
Can someone please suggest how we can implement this logic? Each payment in a payment list can have multiple attributes which should not be modified. For example: if we have 5 payments in existing payment list and each payment has 2 Transactions each, then new payment list will have 10 payment objects.
Edit: @Nikolas Charalambidis answer works perfectly fine.
To set it back to xml document. Can someone pls let me know if this approach is fine
q.forEach(p->{
//q.forEach(p->{
BigDecimal s = pmtInf.getSum();
short t = pmtInf.getNum();
cs.getGH().setSum(s);
cs.getGH().setNum((short) t);
cs.getPmt().add(p);
document.setCstmrCdtTrfInitn(cs);
/str.add(getJAXBObjectToXML(document, Doc.class));
cs.getPmtInf().clear();
});
The solution is simple. You need to iterate through each payment ( Ptm
) and then through each transaction ( Transaction
) while retaining the reference to the payment ( Ptm
) for creating the identical one with a single-item list of the transaction ( Transaction
). There are three basic ways I can come up with from scratch and they don't differ in principle:
Java 7 and earlier (though this solution is ok to be used in the later versions):
List<Pmt> list = new ArrayList<>();
pmtList.forEach(p ->
p.getTrList().forEach(tr ->
list.add(new Pmt(p.getId(), p.getB(), singletonList(tr)))));
Java 8 - Java 15 (though this solution is ok to be used in the later versions):
List<Pmt> list = pmtList.stream()
.flatMap(p -> p.getTrList()
.stream()
.map(tr -> new Pmt(p.getId(), p.getB(), singletonList(tr))))
.collect(Collectors.toList());
Java 16 and newer:
List<Pmt> list = pmtList.stream()
.mapMulti((Pmt p, Consumer<Pmt> c) -> {
p.getTrList().forEach(tr ->
c.accept(new Pmt(p.getId(), p.getB(), singletonList(tr))));
})
.toList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.