Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14096

Cast HashMap<String, Integer> with HashMap<String, Double>

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()) );
}

Upvotes: 1

Views: 1592

Answers (3)

Flown
Flown

Reputation: 11740

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()));

Upvotes: 0

ersdiniz
ersdiniz

Reputation: 38

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

Upvotes: 2

Siva Kumar
Siva Kumar

Reputation: 2006

You could not cast the hashmap.

entrySet() will give better performance approach.

Upvotes: 0

Related Questions