I have Work_Order_Sequence__c
and UniqueKey__c
field on Work Order object. In my method I wish to create a Map which has a Key => UniqueKey__c
and Value=> List<WorkOrder> (sorted)
. Basically grouping all the sorted work orders by UniqueKey__c
. Unfortunately I do not have option to do ORDER BY
as these WO are not in database.
Example:
--------
#. Work_Order_Sequence__c UniqueKey__c
WO1 3 abc
WO2 1 abc
WO3 2 abc
WO4 1 xyz
WO5 3 xyz
WO6 2 xyz
The method I am creating takes the unsorted List<WorkOrder>
as parameter.
I tried the below approach to sort the WorkOrders and group them by UniqueKey__c
. However I see there are two for loops
involved here. Is there a more efficient way or more simplified way of achieving this?
What I tried:
public with sharing class SortClass {
public Map<String, List<WorkOrder>> groupWorkOrders(List<WorkOrder> woList) {
Map<String, List<WorkOrderWrapper>> mapOfWrapByUnqKey = new Map<String, List<WorkOrderWrapper>>();
Map<String, List<WorkOrder>> mapOfWOByUnqKey = new Map<String, List<WorkOrder>>();
for (WorkOrder w : woList) {
if (mapOfWOByUnqKey.containskey(w.uniqueKey__c)) {
mapOfWOByUnqKey.get(w.uniqueKey__c).add(w);
mapOfWrapByUnqKey.get(w.uniqueKey__c).add(new WorkOrderWrapper(w));
} else {
mapOfWOByUnqKey.put(w.uniqueKey__c, new List<WorkOrder>{ w });
mapOfWrapByUnqKey.put(w.uniqueKey__c, new List<WorkOrderWrapper>{ new WorkOrderWrapper(w) });
}
}
for (String s : mapOfWrapByUnqKey.keyset()) {
mapOfWrapByUnqKey.get(s).sort();
List<WorkOrder> wolst = new List<WorkOrder>();
for (WorkOrderWrapper wr : mapOfWrapByUnqKey.get(s)) {
wolst.add(wr.wo);
}
mapOfWOByUnqKey.put(s, wolst);
}
return mapOfWOByUnqKey;
}
public class WorkOrderWrapper implements Comparable {
public WorkOrder wo;
// Constructor
public WorkOrderWrapper(WorkOrder w) {
wo = w;
}
// Compare workOrders based on the WorkOrder seq.
public Integer compareTo(Object compareTo) {
// Cast argument to WorkOrderWrapper
WorkOrderWrapper compareTowo = (WorkOrderWrapper) compareTo;
// The return value of 0 indicates that both elements are equal.
Integer returnValue = 0;
if (wo.Work_Order_Sequence__c > compareTowo.wo.Work_Order_Sequence__c) {
// Set return value to a positive value.
returnValue = 1;
} else if (wo.Work_Order_Sequence__c < compareTowo.wo.Work_Order_Sequence__c) {
// Set return value to a negative value.
returnValue = -1;
}
return returnValue;
}
}
}