Write a method called rarest that accepts a map whose keys are strings and whose values are integers as a parameter and returns the integer value that occurs the fewest times in the map. If there is a tie, return the smaller integer value. If the map is empty, throw an exception.
package collections;
import java.util.HashMap;
import java.util.Map;
public class RareInteger {
public static int rarest(Map<String, Integer> original) {
// crete map to store our new key value pairs
HashMap<Integer, Integer> newMap = new HashMap<Integer, Integer>();
// initialize rare with max value
int rare = Integer.MAX_VALUE;
int rareInt = rare;
// loop through all the keys in the map
for (String key : original.keySet()) {
int value = original.get(key);
// if it already contains increment the value by one
if (newMap.containsKey(value)) {
newMap.put(value, newMap.get(value) + 1);
} else {
// else put the valuse as key and 1 as its value
newMap.put(value, 1);
}
}
for (int key : newMap.keySet()) {
int value = newMap.get(key);
// loop through all the keys in the map
if (value < rare) {
rareInt = key;
rare = value;
} else if (value == rare) {
if (key < rareInt)
rareInt = key;
}
}
return rareInt;
}
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Janet", 7);
map.put("kishore", 19);
map.put("wiliam", 89);
map.put("vala", 35);
map.put("mar", 5);
map.put("kisfsd", 33);
map.put("fiam", 89);
map.put("nila", 7);
map.put("arty", 12);
map.put("Jet", 8);
map.put("hore", 23);
map.put("liam", 9);
map.put("sila", 8);
System.out.print("the integer value that occures fewest times in the map is: " +rarest(map));
}
}
Output:
the integer value that occures fewest times in the map is: 5