【问题标题】:How can i convert my HashMap Key from float to Integer in java?java - 如何在java中将我的HashMap Key从float转换为Integer?
【发布时间】:2021-10-01 10:32:19
【问题描述】:
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 有一个整数类型键,而 map1 有一个浮点类型键,因此我想将我的 map1 键转换为整数。所以我可以轻松地将这些键存储到 map2 中

map2.putAll(map1);



  }

}

【问题讨论】:

  • 如果 map1 包含键 10.1、10.2、10.9,您希望发生什么?
  • 是的,它只会从中添加一个。但实际上,我只是想知道这是否可能。

标签: java hashmap type-conversion


【解决方案1】:

您可以在将密钥更改为Integer 后,遍历map1 并将每个条目插入map2

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

【讨论】:

  • 谢谢它的工作
【解决方案2】:

迭代条目并转换键值。

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 订购的本质。

【讨论】:

  • 感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
相关资源
最近更新 更多