Question

How does the following method work?

Pairs is a LinkedHashMap, I am just not sure of the enhanced for loop and how it works with the hasmap. i.e the keyset.

/**
         * Finds all names in the initial input list that match phonetically with
         * the supplied name
         * 
         * @param phoneticName
         *            The name for which you want to find matches
         * @return An ArrayList of all phonetically matching names
         */
        public ArrayList<String> findMatchingNames(String phoneticName) {
            ArrayList<String> matchedNames = new ArrayList<>();

            for (String s : Pairs.keySet()) {
                if (phoneticName.equals(Pairs.get(s))) {
                    matchedNames.add(s);
                }
            }
            return matchedNames;
        }
    }
Was it helpful?

Solution

The method traverses all the keys currently in LinkedHashMap:

for (String s : Pairs.keySet()) {

If the value associated with this key within the map equals to the passed argument, we save this key inside the list matchedNames:

if (phoneticName.equals(Pairs.get(s))) {
    matchedNames.add(s);
}

And then we return the list of keys, whose values equals to the passed argument phoneticName.

OTHER TIPS

Basically enhanced for loop works with all the collection which are iterable.

so in our case if we take LinkedHashMap , it is not iterable directly because 1)its not a collection , its a key value pair.

2)we cant iterate to get key value directly.

so we need to take keys and put them into some collection, say set.

why set? because map will have unique(no duplicate) keys so they implemented a method inside a map called keySet.

so map.keySet() returns the set of keys.

now we can iterate easily using for loop as set is iterable.

so we have written

for (String s : Pairs.keySet())

now each s in the above syntax is a string coming from keySet one by one on every iteration.

Now compare passed name with value for the corresponding key inside a map and if they are equal add that name to the list

Pairs.get(s) -> gives value of the map for the key s.

if (phoneticName.equals(Pairs.get(s))) {
    matchedNames.add(s);
}

at the end of method return this newly formed matched list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top