如何将 java 中的 HashMap 键从浮点数转换为整数?

How can i convert my HashMap Key from float to Integer in java?

import java.util.Map;
import java.util.HashMap;

public class q9 {
public static void main(String[] args) {
    Map<Float, String> map1 = new HashMap<>();
    Map<Integer, String>map2= new HashMap<>();

我想将所有 map1 键从浮点数转换为整数。

    map1.put(11.1f, "black");
    map1.put(12.1f, "brown");
    map1.put(13.1f, "Grey");
    map1.put(14.1f, "blue");

在此,我想将 map1 HashMap 存储到 map2 HashMap,但 map2 有一个 Integer 类型的键,而 map1 有一个 float 类型的键,因此我想将我的 map1 键转换为 Integer。所以我可以轻松地将这些键存储到 map2

map2.putAll(map1);



  }

}

迭代条目并转换键值。

for (Map.Entry<Float, String> entry : map1.entrySet()) {
    map2.put((int)(float)entry.getKey(), entry.getValue());
}

我们需要双重施法来触发float自动拆箱和int自动装箱。

另一种方法是手动直接拆箱到 int,然后让编译器自动装箱。

for (Map.Entry<Float, String> entry : map1.entrySet()) {
    map2.put(entry.getKey().intValue(), entry.getValue());
}

警告:如果两个或多个 float 值转换为相同的 int 值,则 任意 哪个条目获胜。这就是 HashMap 排序的本质。

在将键更改为 Integer:

后,您可以遍历 map1 并将每个条目插入 map2
for(Map.Entry<Float, String> entry : map1.entrySet()) 
  map2.put(entry.getKey().intValue(), entry.getValue());