【问题标题】:Question how to get value from map on map like this code质疑如何从地图上的地图中获取价值,就像这段代码一样
【发布时间】:2020-09-28 09:17:27
【问题描述】:

我有这样的源代码

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

问候,

法德

【问题讨论】:

  • 遍历地图并在第二张地图上添加所需的地图(或您需要的任何数据结构)
  • 你的代码能编译成功吗?
  • 尽管您的代码无法编译,但您应该考虑使用其他数据结构。

标签: java hashmap


【解决方案1】:

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

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

【讨论】:

  • 如果这对您有帮助,您可以接受它作为您问题的答案。
猜你喜欢
  • 2016-04-04
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 2021-01-01
相关资源
最近更新 更多