【问题标题】:Need to put one custom hashmap into another hashmap需要将一个自定义 hashmap 放入另一个 hashmap
【发布时间】:2018-09-22 06:42:34
【问题描述】:

我有以下地图:

HashMap<Integer, HashMap<Integer, Employee>> hmap = new HashMap<Integer,HashMap<Integer, Employee>>();

HashMap<Integer, Employee> emap = new HashMap<Integer, Employee>();

我正在使用 keyset 将对象从 emap 中取出并比较员工工资。 如果工资低于特定金额,我需要将该映射放入 hmap 中,键为 0,如果高于则键为 1。

for(Integer e: emap.keySet())
    {
        if(emap.get(e).getSalary()<45000.0)
        {
            hmap.put(0,//what should i put here );
        }
        else
        {
            hmap.put(1,//what should i put here );
        }
    }

谢谢。

【问题讨论】:

  • 为什么hmap 也不能是HashMap&lt;Integer, Employee&gt;?如果你有超过 2 张地图,你会怎么做,因为你只有 01 作为 key?
  • hmap 将只有 2 个键,1 和 0。1 表示 emap 的所有有效记录,0 表示所有无效。
  • 您需要将其声明为 Map> 而不是 HashMap。尽可能使用接口类型。
  • 只需使用partitionBy

标签: java collections hashmap


【解决方案1】:

你可以使用两个辅助地图:

Map<Integer, Employee> lowSalaryEmployees = new HashMap<>();  
Map<Integer, Employee> highSalaryEmployees = new HashMap<>();

然后将它们填充到 for 循环中并将它们放入您的hmap

for (Integer k: emap.keySet()) {
    Employee e = emap.get(k);
    if (e.getSalary() < 45000.0) {
        lowSalaryEmployees.put(k, e);
    } else {
        highSalaryEmployees.put(k, e);
    }
}

hmap.put(0, lowSalaryEmployees);
hmap.put(1, highSalaryEmployees);

【讨论】:

    【解决方案2】:

    由于您将hmap 的参数化类型声明为HashMap&lt;Integer, HashMap&lt;Integer, Employee&gt;&gt;,那么您只能将HashMap&lt;Integer,Employee&gt; 类型作为值输出到hmap

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 2017-07-06
      相关资源
      最近更新 更多