[英]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<>();
I want to convert my all map1 keys from float to Integer.我想将我所有的 map1 键从 float 转换为 Integer。
map1.put(11.1f, "black");
map1.put(12.1f, "brown");
map1.put(13.1f, "Grey");
map1.put(14.1f, "blue");
In this, I want to store map1 HashMap to map2 HashMap but map2 has an Integer type key and map1 has a float type key and hence I want to convert my map1 keys to Integer.在此,我想将 map1 HashMap 存储到 map2 HashMap 但 map2 有一个整数类型的键,而 map1 有一个浮点类型的键,因此我想将我的 map1 键转换为整数。 So I can easily store those keys into map2
所以我可以轻松地将这些键存储到 map2 中
map2.putAll(map1);
}
}
You can iterate over map1
and insert each entry to map2
after changing the key to an Integer
:在将键更改为
Integer
后,您可以遍历map1
并将每个条目插入到map2
:
for(Map.Entry<Float, String> entry : map1.entrySet())
map2.put(entry.getKey().intValue(), entry.getValue());
Iterate the entries and cast the key value.迭代条目并转换键值。
for (Map.Entry<Float, String> entry : map1.entrySet()) {
map2.put((int)(float)entry.getKey(), entry.getValue());
}
We need to double-cast to trigger float
auto-unboxing and int
auto-boxing.我们需要双重转换来触发
float
自动拆箱和int
自动装箱。
Alternative is it unbox directly to int
manually, and let the compiler auto-box that.另一种方法是直接手动将
int
拆箱,并让编译器自动将其拆箱。
for (Map.Entry<Float, String> entry : map1.entrySet()) {
map2.put(entry.getKey().intValue(), entry.getValue());
}
Warning: If two or more float
values converts to the same int
value, it is arbitrary which entry wins.警告:如果两个或多个
float
值转换为相同的int
值,则哪个条目获胜是任意的。 That is the nature of HashMap
ordering.这就是
HashMap
排序的本质。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.