gpt4 book ai didi

java 获取 HashMap 键作为整数数组

转载 作者:行者123 更新时间:2023-12-02 21:41:31 29 4
gpt4 key购买 nike

我有一个像这样的 HashMap

public HashMap <String,People> valueHashMap  = new Hashmap();

这里我的 HashMap 的关键是以秒为单位的字符串时间,即我像这样向 hashmap 添加值

long timeSinceEpoch = System.currentTimeMillis()/1000;
valueHashMap.put(
Integer.toString((int)timeSinceEpoch)
, people_obj
);

现在我想将 HashMap 中的所有键放入整数数组列表中。

ArrayList<Integer> intKeys = valueHashMap.keys()...

有什么办法可以做到这一点吗?

最佳答案

没有直接的方法将String列表转换为Integer列表:

  1. 您需要像这样重新定义 valueHashMap:

    public HashMap<Integer, People> valueHashMap  = new HashMap<Integer, People>();

    ....

    ArrayList<Integer> intKeys = new ArrayList<Integer>(valueHashMap.keySet());
  2. 或者你需要循环:

    ArrayList<Integer> intKeys = new ArraList<Integer>();

    for (String stringKey : valueHashMap.keySet())
    intKeys.add(Integer.parseInt(stringKey);
  3. 不过,我建议您使用 Long 作为键:

    public HashMap<Long, People> valueHashMap  = new HashMap<Long, People>();

    那么就不会转换为 int (您可以使用上面的 (1) 和 Long 来代替)

关于java 获取 HashMap 键作为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7412597/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com