首页 > 解决方案 > 询问如何从地图上的地图中获取价值,就像这段代码一样

问题描述

我有这样的源代码

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 的人的姓名如何获得该姓名和他们的年龄?

问候,

福阿德

标签: javahashmap

解决方案


假设我们将您的代码更改为这样编译:

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 岁以上的结果。


推荐阅读