java - 询问如何从地图上的地图中获取价值,就像这段代码一样
问题描述
我有这样的源代码
import java.util.Map;
public class MyClass {
public static void main(String[] args) {
// Create a Map object called people
Map<String, Map<String,Integer>> people = new HashMap<String, Map<String,Integer>>();
// Add keys and values (Name, (Sex,Age))
people.put("John", createMap("M",32));
people.put("Steve", createMap("M",30));
people.put("Angie", createMap("W",33));
for (String i : people.keySet()) {
System.out.println("key: " + i + " value: " + people.get(i));
}
}
}
我的问题是我想获得年龄超过 30 岁的发生性行为 M 的人的姓名如何获得该姓名和他们的年龄?
问候,
福阿德
解决方案
假设我们将您的代码更改为这样编译:
Map<String, Map<String,Integer>> people = new HashMap<String, Map<String,Integer>>();
// Add keys and values (Name, (Sex,Age))
people.put("John", createMap("M",32));
people.put("Steve", createMap("M",30));
people.put("Angie", createMap("W",33));
...
private static Map<String, Integer> createMap(String key, Integer value) {
Map<String, Integer> map = new HashMap<>();
map.put(key, value);
return map;
}
然后,您可以使用这样的循环来过滤具有给定条件的人员:
for (Map.Entry<String, Map<String, Integer>> entry : people.entrySet()) {
if (entry.getValue().containsKey("M") && entry.getValue().get("M") > 30) {
System.out.println("key: " + entry.getKey() + " value: " + people.get(entry.getKey()));
}
}
但如前所述,如果可以,您应该更改用于保存人员信息的数据结构。但是,当您将代码设置为给定时,上述内容将起作用并产生John
男性和 30 岁以上的结果。
推荐阅读
- java - 如何防止已经选择(user1)的表行被另一个(user2)选择?
- angular - Ng 在 IntelliJ Webstorm 或 IDEA 中构建一个 Angular 7 项目
- google-chrome - 有没有办法将 chrome 参数与用户配置文件结合起来?
- javascript - 通过使用 Map Filter 与对象数组进行比较来返回字段
- java - 执行 jar 文件时遇到问题
- php - 如何将图像路径存储在数据库中 - 使用 laravel
- scalatest - 为什么我不能测试一个类的实例是否已定义
- html - 在 Bootstrap 中,如何将所有元素保持在同一行?
- cakephp - 使用 composer 更新 cakephp3 导致缺少依赖项
- postgresql - 如何将整个数据库从 Postgres 迁移到 DynamoDB