In: Computer Science
CS 209 Data Structure
2. Create a method that takes a HashMap and returns the sum of the keys of the HashMap.
3. Create a method that takes a HashMap and returns the sum of all keys and values of the HashMap.
For example, if the input is [1=9, 3=6, 4=9, 6=8, 7=6] then the method should return 59.
A method that takes a HashMap and returns the sum of the keys of the HashMap
public <K, V extends Number> double sumKeys(Map<K, V> map) {
// hashmap with data type of double and method written to get sum of keys
double sum = 0.0d; // defination of sum
for (Number key : map.key()) // take key in for loop
sumkey += key.doubleValue(); // sum+ function will add up all the output given by for loop
return sumkey; // returns sum of all key of HashMap
}
A method that takes a HashMap and returns the sum of all keys and values of the HashMap.
Public sumKeyValue(Map<K, V> map)
// method to return the sum of key and values of Hashmap
{
public <K, V extends Number> double sumKeys(Map<K, V> map)
// method that returns sum of keys
{
double sum = 0.0d;
for (Number key : map.key()) // take key in for loop
sumkey += key.doubleValue();
return sumkey;
}
public <K, V extends Number> double sumValues(Map<K, V> map)
// method that returns sum of values
{
double sum = 0.0d;
for (Number value : map.values()) // take value in for loop
sumvalue += value.doubleValue();
return sumvalue;
}
return sumkey+sumvalue; // returns total sum of keys and values
}