首页 > 解决方案 > 在数组列表的 HashMap 中迭代

问题描述

简而言之-我尝试编写一种方法,该方法应将 的值转换String[] sourceAllPeopleInMyFamilyPerson. 然后,检查此Person实例是否存在于HashMap<String, ArrayList<Person>> allPeople. 如果是这样,我应该将此Person实例添加到HashSet<Person> allPeopleInMyFamily.

Person类包含String personName+ int personAgeHashMap<String, ArrayList<Person>>包含键String personName+ 值array list of Person objects

我写了以下代码。

由于我使用HashMap,我使用entry迭代所有地图。但是由于该条目会检查所有键和值,因此如果找不到对象,这会阻止我使用 return 语句。

请建议我的情况有更好的迭代吗?

    boolean addPerson (String[] sourceAllPeopleInMyFamily) {

        HashMap<String, ArrayList<Person>> allPeople = pointer to another initialized HashMap in another package;

        HashSet<Person> allPeopleInMyFamily = new HashSet<Person>();

        for (Map.Entry<String, ArrayList<Person>> entry : allPeople.entrySet()) {

            for (String sourcePersonInMyFamily : sourceAllPeopleInMyFamily) {

                Person personInMyFamily = new Person (sourcePersonInMyFamily); // Create a new person based on sourceAllPeopleInMyFamily array

                if (entry.getValue().contains(personInMyFamily) { // Check if personInMyFamily exists in all people set

                    if (!allPeopleInMyFamily.add(personInMyFamily))
                        return false;

                // } else { return false; } ???????

                }
            }
        }
    }

标签: javaloopshashmaphashset

解决方案


推荐阅读