1

Why cast does not work in this case directly with

HashMap<String, Double> mapDouble = (HashMap<String, Integer>) mapInteger;

Is there an easier way than a loop ?

HashMap<String, Double> mapDouble;
for (Map.Entry<String,Integer> entry : mapInteger.entrySet()) {
    mapDouble.put(entry.getKey(), new Double(entry.getValue()) );
}
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99

3 Answers3

2

Sorry, but you need a loop! You have to go all the mapInteger to convert the values one by one.

ersdiniz
  • 38
  • 4
0

You could not cast the hashmap.

entrySet() will give better performance approach.

Siva Kumar
  • 1,983
  • 3
  • 14
  • 26
0

It would be easier to use Map<String, Number>.

Map<String, Number> map = new HashMap<>();
for (int i = 0; i < 100; i++) {
    map.put(Integer.toString(i), i);
}
map.forEach((k, v) -> System.out.println(k + " -> " + v.doubleValue()));
Flown
  • 11,480
  • 3
  • 45
  • 62