In: Computer Science
Create a method that takes a HashMap<Integer, Integer> and returns the sum of the keys of the HashMap.
CODE:
import java.util.*;
class Main {
public static int sumHashmap(HashMap<Integer,Integer> hm){
int sum=0;
for(Map.Entry<Integer,Integer>m : hm.entrySet()){
// get current key and int value of the current Integer object
sum+=m.getKey().intValue();
}
return sum;
}
public static void main(String[] args) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();//Creating HashMap
map.put(1,10);
map.put(2,20);
map.put(3,30);
map.put(4,40);
// calling the sun function with a HashMap
int result=sumHashmap(map);
System.out.println(result);
}
}
OUTPUT:
Please
upvote if you like my answer and comment below if you have
any queries or need any further explanation.