java - 在数组列表的 HashMap 中迭代
问题描述
简而言之-我尝试编写一种方法,该方法应将 的值转换String[] sourceAllPeopleInMyFamily
为Person
. 然后,检查此Person
实例是否存在于HashMap<String, ArrayList<Person>> allPeople
. 如果是这样,我应该将此Person
实例添加到HashSet<Person> allPeopleInMyFamily
.
Person
类包含String personName
+ int personAge
。
HashMap<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; } ???????
}
}
}
}
解决方案
推荐阅读
- database - 在不扫描集合/表的情况下跟踪字段的值分布
- node.js - 节点js amqplib,消费者缓存中的回调来自父函数的参数
- c - dbus 信号中收到的消息与发送的数据不匹配
- javascript - 为什么我的图像和信息不能在我的 React localhost 上呈现?
- react-native - 适用于 React Native 的 FreshChat SDK:横向模式
- web-component - 可以请求另一个 HTML URL 并将其注入它的影子 DOM 的 Web 组件
- sql - 日期函数的问题
- api - 将带有文件的 Postman 表单数据请求转换为 .NET Core API 的 cURL
- c++ - Xcode 13 无法在 Rosetta 下编译 SFML c++ 程序
- hasura - Hasura 迁移存储在 DB 中的什么位置?