[SalesForce] Convert Map to List using SObject field values

I have a Map of Financial__c records, stored like so:

Map<Id, Financial__c> idWithParent = new Map<Id, Financial__c>();

The Id part belongs to a different objects record, like a service or something, pulled from a lookup field on the Financial Record itself. Then we store the entire Financial record the lookup ID was pulled from.

On the individual Financial__c records is a Status field with one of two values: Paid or New.

I can cast the Financial__c records from a map into a list like so:

List<Financial__c> finRecords = idWithParent.values();

My question, is can I cast only specific records from the list using that status field, and ignore the rest?

Something like this:

List<Financial__c> paidOnly = idWithParent.values().onlyPaidStatusRecords.onlyAddPaidItems()?

I dug through the map documentation but am having issues figuring this out. I know I can iterate through the map, but was hoping to eliminate iterating the long way if I can do it quickly doing something like above.

Is this possible? If so, how is it done?

Best Answer

There is no out of the box way to do what you want. You have to iterate. You can write some simple filter mechanisms or use a library like Selector to make your life easier. With that library, you can do things like:

List<Financial__c> paidOnly = Select.Field.isEqual(Financial__c.Status__c, 'Paid')
    .filter(idWithParent.values());

If your just checking simple equality, it's pretty easy to genericize sans library.

public static List<SObject> filterIsEqual
    (SObjectField field, Object value, List<SObject> records)
{
    List<SObject> output = new List<SObject>();
    for (SObject record : records)
        if (record.get(field) == value)
            output.add(record);
    return output;
}
Related Topic