SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:19 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.