Reputation: 67
Hello Stack Overflow community,
I have encountered a challenge while working with Java's HashMaps. I have two HashMaps, map1 and map2, where map1 has keys of type Float and map2 has keys of type Integer. Now, I need to copy the entries from map1 to map2.
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<>();
// Adding entries to map1
map1.put(11.1f, "black");
map1.put(12.1f, "brown");
map1.put(13.1f, "Grey");
map1.put(14.1f, "blue");
// Now, I want to copy the entries from map1 to map2 with Integer keys
// map2.putAll(map1); // This line gives a compilation error due to key type mismatch
// How can I convert the Float keys from map1 to Integer keys to successfully copy entries to map2?
}
}
I would appreciate guidance on how to convert the keys from Float to Integer so that I can successfully copy the entries from map1 to map2. Any insights, code examples, or best practices would be highly valuable.
Thank you for your assistance!
Upvotes: 0
Views: 838
Reputation: 28414
You can iterate over map1
and insert each entry to map2
after changing the key to an Integer
:
for(Map.Entry<Float, String> entry : map1.entrySet())
map2.put(entry.getKey().intValue(), entry.getValue());
Upvotes: 5
Reputation: 159086
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.
Alternative is it unbox directly to int
manually, and let the compiler auto-box that.
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. That is the nature of HashMap
ordering.
Upvotes: 2