How to implement findIndex functionality for a Map<String, String> in Apex

How to implement findIndex functionality for a Map<String, String> in Apex

Background

I am in the process of developing a method specifically designed to pinpoint the key within a Map<String, String> structure when it corresponds to a particular value I'm looking for. My affinity for JavaScript has significantly influenced my approach to this problem. It brought to mind the findIndex function, which I've often utilized to achieve similar objectives in JavaScript. This function has always stood out to me for its efficiency and elegance in array manipulation tasks. Drawing inspiration from this, I'm keen on implementing a similar solution within the Apex environment, aiming to blend the robustness of Salesforce's backend capabilities with the intuitive functionality that findIndex offers in the JavaScript ecosystem. This endeavor is not just about solving the task at hand but also about bridging my fondness for JavaScript's methodologies with the powerful, object-oriented architecture of Apex, thereby enhancing the functionality and efficiency of Salesforce applications.

Logic

To implement a findIndex functionality in Apex for a Map<String, String>, akin to what JavaScript offers, one must adeptly traverse through the entries of the map, meticulously evaluating each against a predetermined condition. Unlike arrays or lists, maps in Apex do not inherently possess an ordered index. Therefore, a common and ingenious workaround involves employing a list to mimic this functionality. This technique is particularly useful when the task at hand requires pinpointing the "index" of a specific key-value pair that fulfills a certain condition, thereby blending the flexibility of JavaScript with the robust structure of Apex in a seamless and efficient manner.

Implementation

public class MapUtils {
    /**
     * Finds the index of the first entry in a Map<String, String> that satisfies the specified condition.
     * 
     * @param map The map to search.
     * @param condition The condition to evaluate for each entry.
     * @return The index of the first map entry that satisfies the condition, or -1 if no such entry is found.
     */
    public static Integer findIndex(Map<String, String> map, MapCondition condition) {
        // Convert the map keys to a list to have an index-based order
        List<String> keys = new List<String>(map.keySet());

        // Iterate over the list of keys to find the first one that meets the condition
        for (Integer i = 0; i < keys.size(); i++) {
            String key = keys[i];
            String value = map.get(key);

            // Check if the current entry satisfies the condition
            if (condition.evaluate(key, value)) {
                return i; // Return the index if the condition is met
            }
        }

        return -1; // Return -1 if no entry satisfies the condition
    }

    /**
     * Interface for defining a condition to evaluate against map entries.
     */
    public interface MapCondition {
        Boolean evaluate(String key, String value);
    }
}        

Usage

// Example usage
Map<String, String> myMap = new Map<String, String>{
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry'
};

// Define a condition that checks if the value starts with 'b'
MapUtils.MapCondition condition = new MapUtils.MapCondition() {
    public Boolean evaluate(String key, String value) {
        return value.startsWith('b');
    }
};

// Find the index of the first entry that satisfies the condition
Integer index = MapUtils.findIndex(myMap, condition);
System.debug('Index: ' + index); // Should output 1, assuming the map retains the insertion order        

Note

In Apex, the sequence in which map keys are iterated typically aligns with the order of their insertion. However, it's important to note that this behavior isn't formally guaranteed by official documentation. Consequently, if maintaining a specific order is critical for your application, consider utilizing a List or maintaining an auxiliary list of keys to reliably preserve order consistency. This approach safeguards against potential discrepancies and ensures that your data structure meets the precise requirements of your use case.


To view or add a comment, sign in

Others also viewed

Explore content categories