简体   繁体   English

LinkedHashMap,方法内的功能?

[英]LinkedHashMap, functionality within method?

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. Pairs是一个LinkedHashMap,我不确定增强的for循环以及它如何与hasmap一起工作。 ie 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;
        }
    }

The method traverses all the keys currently in LinkedHashMap : 该方法遍历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 : 如果映射中与此键相关联的值等于传递的参数,则将该键保存在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 . 然后,我们返回键的列表,其值等于传递的参数phoneticName

Basically enhanced for loop works with all the collection which are iterable. 基本上增强了for循环,可与所有可迭代的集合一起使用。

so in our case if we take LinkedHashMap , it is not iterable directly because 1)its not a collection , its a key value pair. 因此,在本例中,如果我们采用LinkedHashMap,则它是不可直接迭代的,因为1)它不是一个collection,而是一个键值对。

2)we cant iterate to get key value directly. 2)我们不能迭代直接获得键值。

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. 因为地图将具有唯一(无重复)键,所以它们在地图内部实现了一个称为keySet的方法。

so map.keySet() returns the set of keys. 因此map.keySet()返回键集。

now we can iterate easily using for loop as set is iterable. 现在我们可以轻松地使用for循环进行迭代,因为set可以迭代。

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. 现在,以上语法中的每个s都是一个字符串,该字符串在每次迭代中都一个一个地来自keySet。

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. Pairs.get(s) ->给出键s的映射值。

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

at the end of method return this newly formed matched list. 在方法末尾,返回此新形成的匹配列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM