I have an already sorted list of objects, and need to perform a "group by" and assign a sequence number to each object in the group.
[Essentially, I am trying to mimic the effect of a sql window function such as "seq = row_number() over (partition by cust_id)"]
Right now, I am achieving this using the below code, but would like to learn if there is a different way to do it using Java 8 features like stream() or forEach(). Thanks for the help.
int count = 0;
String prev_cust_id = "";
// OrdersList is already sorted by cust_id
for (Order o : orderList) {
// reset index for each new group
if (!o.cust_id.equals(prev_cust_id))
count = 0;
o.seq = ++count;
prev_cust_id = o.cust_id;
}
Update: I was also able to achieve the same with below code, but it is less readable and seems more inefficient. Is there is a better way.
orderList.get(0).seq = 1;
IntStream.range(1, orderList.size())
.forEach(i -> orderList.get(i).seq = orderList.get(i).cust_id.equals(orderList.get(i-1).cust_id) ? OrdersList.get(i-1).seq + 1 : 1);