Friday, June 28, 2024

Finding a Key’s Index in Java LinkedHashMap

Finding a Key’s Index in Java LinkedHashMap

The Java LinkedHashMap class combines a hash table and linked list to maintain predictable iteration order, unlike HashMap. However, LinkedHashMap does not provide a direct method to get the position (index) of a key-value pair. This article explores methods to retrieve the index of a key-value pair in a LinkedHashMap.

1. Using Iteration


One straightforward method is to iterate through the entrySet of the LinkedHashMap, comparing each key with the target key and returning the index when a match is found.

LinkedHashMapIterationApproach.java

public class LinkedHashMapIteration {
 
    public static void main(String[] args) {
         
        // Create a LinkedHashMap with Integer keys and String values
        LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put(101, "Alice");
        linkedHashMap.put(202, "Bob");
        linkedHashMap.put(303, "Charlie");
        linkedHashMap.put(404, "David");
 
        // Key to find position for
        Integer key = 303;
         
        // Find the position of the key using iteration approach
        int position = getPositionOfKey(linkedHashMap, key);
         
        // Output the result
        System.out.println("LinkedHashMap: " + linkedHashMap);
        System.out.println("Finding position of key: " + key);
        System.out.println("Position: " + position);
        //System.out.println("The position of the key \"" + key + "\" is: " + position);
    }
 
    public static <K, V> int getPositionOfKey(LinkedHashMap<K, V> map, K key) {
        int index = 0;
        for (Map.Entry<K, V> entry : map.entrySet()) {
            if (entry.getKey().equals(key)) {
                return index;
            }
            index++;
        }
        return -1; // Key not found
    }
}

Output:

LinkedHashMap: {101=Alice, 202=Bob, 303=Charlie, 404=David}
Finding position of key: 303
Position: 2

In this example, we create a LinkedHashMap<Integer, String> and populate it with key-value pairs. Next, we specify key = 303 to demonstrate finding the position of the key 303. The getPositionOfKey method iterates through the entrySet() of the LinkedHashMap and compares each key with key. Upon finding a match (key = 303), it returns the position (index) 2 since indexing starts from 0.

2. Using Key Set Conversion


Using this approach, we convert the key set to a list and then find the index of the key.

LinkedHashMapKeySetConversion.java

public class LinkedHashMapKeySetConversion {
 
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("January", 1);
        linkedHashMap.put("February", 2);
        linkedHashMap.put("March", 3);
        linkedHashMap.put("April", 4);
 
        String key = "January";
        int position = getPositionOfKey(linkedHashMap, key);
        System.out.println("The position of the key \"" + key + "\" is: " + position);
    }
 
    public static <K, V> int getPositionOfKey(LinkedHashMap<K, V> map, K key) {
        List<K> keyList = new ArrayList<>(map.keySet());
        return keyList.indexOf(key);
    }
}

Here, the keySet of the LinkedHashMap is converted to an ArrayList. The indexOf method of ArrayList is then used to find the index of the key.

Output:

The position of the key "January" is: 0

3. Using Stream API (Java 8+)


With Java 8 and higher, the Stream API offers a straightforward way to solve this issue using functional programming principles.

LinkedHashMapStreamApiApproach.java

public class LinkedHashMapStreamApiApproach {
 
    public static int findKeyPosition(LinkedHashMap<String, Integer> map, String key) {
        int position = 0;
        Optional<String> foundKey = map.entrySet().stream()
                .filter(entry -> entry.getKey().equals(key))
                .map(Map.Entry::getKey)
                .findFirst();
 
        if (foundKey.isPresent()) {
            // Key found, iterate again to count position
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                if (entry.getKey().equals(key)) {
                    return position;
                }
                position++;
            }
        }
        return -1; // Key not found
    }
 
    public static void main(String[] args) {
         
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("apple", 10);
        map.put("banana", 20);
        map.put("cherry", 30);
 
        int position = findKeyPosition(map, "banana");
 
        if (position != -1) {
            System.out.println("Key 'banana' found at position: " + position);
        } else {
            System.out.println("Key 'banana' not found");
        }
    }
}

In this approach, we use entrySet().stream() to create a Stream of key-value pairs from the map and use filter to filter the stream to keep only entries where the key matches the target key. We use map(Map.Entry::getKey) is to extract just the keys from the filtered entries and use findFirst to retrieve the first matching key wrapped in an Optional. If the Optional contains a value (meaning the key was found), we iterate through the entire entrySet again.

Inside the loop, we compare the current entry’s key with the target key. If there’s a match, we return the current position as it represents the target key’s position based on insertion order.

4. Using keySet() and List.copyOf() (Java 10+)


This approach leverages the List.copyOf() method to create a list from the key set and then find the index of the key.

LinkedHashMapListCopyOf.java

public class LinkedHashMapListCopyOf {
 
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("apple", 10);
        linkedHashMap.put("banana", 20);
        linkedHashMap.put("cherry", 30);
        linkedHashMap.put("orange", 40);
 
        String key = "orange";
        int position = getPositionOfKey(linkedHashMap, key);
        System.out.println("The position of the key \"" + key + "\" is: " + position);
    }
 
    public static <K, V> int getPositionOfKey(LinkedHashMap<K, V> map, K key) {
        List<K> keyList = List.copyOf(map.keySet());
        return keyList.indexOf(key);
    }
}

In this approach, List.copyOf(map.keySet()) method creates an unmodifiable copy of the key set from the LinkedHashMap and we use keyList.indexOf(key method to return the index of the specified key in the list. The output is:

The Posotion of the key "orange" is: 3

Example Output Using List.copyOf for Java LinkedHashMap Key Position

5. Conclusion

In this article, we explored several methods to find the position of a key-value pair in a Java LinkedHashMap. We began with a straightforward iteration approach, followed by converting the key set to a list for direct index retrieval. We also demonstrated the power of Java 8’s Stream API for a more functional programming solution. Additionally, we leveraged Java 10’s List.copyOf() method to create an unmodifiable list from the key set, facilitating easy position finding. Each method showcases different aspects of Java’s rich API and highlights various ways to achieve the same goal.

Source: javacodegeeks.com

Related Posts

0 comments:

Post a Comment