[英]How to transform to create a new List such that each object in list has only one element in the nested list each using Java?
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?如何转换以创建一个新的付款列表来替换当前的付款列表 ( pmtList
),以便每个付款 object 只有一个Transaction
,每个使用 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.例如:如果我们现有的支付列表中有 5 个支付,每个支付都有 2 个交易,那么新的支付列表将有 10 个支付对象。
Edit: @Nikolas Charalambidis answer works perfectly fine.编辑:@Nikolas Charalambidis 的回答非常好。
To set it back to xml document.将其设置回 xml 文件。 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
).您需要遍历每笔付款 ( Ptm
),然后遍历每笔交易 ( Transaction
),同时保留对付款 ( Ptm
) 的引用,以便使用交易的单项列表创建相同的付款 ( 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): Java 7及更早版本(尽管此解决方案可以在更高版本中使用):
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): Java 8 - Java 15 (虽然这个解决方案可以在以后的版本中使用):
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: Java 16及更新:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.