我有一个包含以下信息的对象
TransHdr:id,order_num
TransItem:hdr_id,product_code,refnum,qty(子记录)
transHdr.id = transItem.hdr_id
如果说在TransItem中可以找到3条记录,
大衣,112,10
大衣,112,6
parkB,113,10
我想基于引用句柄对它进行分组,意味着我的结果将是
大衣,112,的 16
parkB,113,10
我需要一个循环对象(项级别)并需要将transHdr对象返回到其他函数的方法。无论如何要这样做?
for (java.util.Iterator<ITransItem> groupTransItems = TransHdr.getTransItems().iterator();
groupTransItems.hasNext();) {
ITransItem _TransItem = groupTransItems.next();
if (null!=_TransItem.getRefNum()){
<question here..how do i group and sum up my item and become only 1 record?>
}
}
return newGroupingTransHdr;
}
答案 0 :(得分:0)
创建一个新的Map
,其中refnum为key,qty为value。
Map<String,Integer> qtyMap=new HashMap<String,Integer>();
迭代时,尝试
String refNum=transItem.getRefNum();
// Mark for removal ? if this is not the first item in the list with the refnum
boolean remove=true;
Integer currentQty=qtyMap.get(refNum);
if(currentQty==null){
currentQty=0;
// this doesnt exist already in the map, this is the first item with this reference
// number in the list, so you should keep this without removing
remove=false;
}
currentQty=currentQty+transItem.getQty();
qtyMap.put(refNum,currentQty);
// if the remove is true then remove this item from the list.
if(remove){
groupTransItems.remove();
}
这将总结地图中refnum的数量,一旦你的迭代结束,地图就会得到每个refnum的数量总和。您将不得不再次迭代列表以将当前数量设置为地图中的每个项目[编辑]: - 添加了迭代时间删除。
答案 1 :(得分:0)
与此post中建议的解决方案类似。您可以使用ref_num作为键,将TransItem作为值。
TransHdr transHdr; // Externally given
Map<String, ITransItem> collapsedItems = new HashMap<String, ITransItem>();
List<ITransItem> items = transHdr.getItems();
transHdr.setItems(new ArrayList<ItransItem>());
for (ITransItem item : items) {
String ref_num = item.getRefNum();
ITransItem collapsedItem = collapsedItems.get(ref_num);
if (collapsedItem == null) {
collapsedItems.put(ref_num, item);
} else {
int qnt = item.getQnt();
collapsedItem.setQnt(collapsedItem.getQunt() + qnt);
}
}
transHdr.setItems(new ArrayList<ITransItem>(collapsedItems.values()));
答案 2 :(得分:0)
另一种实现目标的方法是在TransHdr
类的add方法中嵌入逻辑。
pulic class TransHdr {
private String id;
private int orderNumber;
private Map<String, ITransItem> items;
public TransHdr(String id, int orderNumber) {
this.id = id;
this.orderNumber = orderNumber;
this.items = new HashMap<String, ITransItem>();
}
public void addItem(ITransItem item) {
String ref = item.getRefNum();
ITransItem currentItem = items.get(ref);
if (currentItem == null) {
items.put(ref, item);
} else {
int qnt = item.getQnt();
currentItem.setQnt(currentItem.getQnt() + qnt);
}
}
public Set<ITransItem> getItems() {
return items.values();
}
}
正如您所看到的,有多种方法可以做到这一点。适当的解决方案取决于您的要求和用例。