I'm currently working on an order submission feature for a medical product. Its very simple, what I have to do is just:
- query multiple tables (*source of the issue, tables joined without using unique key and this is out of our control, causing the query result with duplicate of same record)
- combine data of all 3 tables into a single payload to submit to manufacturer/supplier
- Extra step to take, loop the list of all orders retrieved from step 2 and insert
orderNobased on today date + counter starting from 1
The Problem: After running stream().map() of the 10 records I got (i.e. containing 2 sets of duplicates due to query issue as stated above), I would be expecting the order number to be [yyyyMMdd0001,yyyyMMdd0002,yyyyMMdd0003,yyyyMMdd0004,yyyyMMdd0005,yyyyMMdd0006,yyyyMMdd0007,yyyyMMdd0008,yyyyMMdd0009,yyyyMMdd0010], However what I really got was [yyyyMMdd0009,yyyyMMdd0010,yyyyMMdd0003,yyyyMMdd0004,yyyyMMdd0005,yyyyMMdd0006,yyyyMMdd0007,yyyyMMdd0008,yyyyMMdd0009,yyyyMMdd0010]
After checking, I found that the purchaseNo which was missing, i.e. yyyyMMdd0001, yyyyMMdd0002 was the duplicate copy of yyyyMMdd0009 and yyyyMMdd0010 but I did not expect that the record would be replaced like this.
Example Code When stream map through the list to insert purchaseNo:
AtomicInteger counter = new AtomicInteger(1);
return orderRepository.retrieveOrderByDate(date)
.stream()
.map(order -> {
var currentCount = String.format("%06d", counter.getAndIncrement());
var purchaseNo = LocalDate.now().format(DATE_FORMAT) + currentCount;
order.setPurchaseNo(purchaseNo);
return order;
}).collect(toList());
Here is roughly what the Order Entity looks like:
public class OrderEntity implments Serializable {
@Transient
private String purchaseNo;
@Id
@Column(name="product_code")
private String productCode;
@Id
@Column(name="recipient_id")
private String recipientId;
//many others recipient and product and shipment related fields
}
I have tried and found the same even when using .forEach() and at this stage assumed that this is the behaviour of stream() in general... but still dont quite understand it.
Would like to get help to understand this behavior from using Java Stream. Thanks!