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:15 | ISBN:9780136091813 | Edition: 2

Question

Write a method maxOccurrences that accepts a list of integers as a parameter and returns the number of times the most frequently occurring integer (the “mode”) occurs in the list. Solve this problem using a map as auxiliary storage. If the list is empty, return 0.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class MaxOccurrance {
 
    // this method takes the list argument
	public static int maxOccurrences(List<Integer> list) {
       
        // we use hashmap to store the element as key and number of times it repeats in 
        // in value, and finally return key which has the max value(i.e, most times it          
        // repeated
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

     // set the mode to 0 initilally
		int mode = 0;

		for (int key : list) {
			if (map.containsKey(key)) {
				map.put(key, map.get(key) + 1);
			} else
				map.put(key, 1);

             // updates the mode value for every iterate
			if (map.get(key) > mode)
				mode = map.get(key);
		}

		return mode;

	}

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();
		Collections.addAll(list, 5,5, 6, 2, 8, 8, 4, 5, 2, 4, 21, 7, 0, 6, 54, 2, 5, 8, 6);
		System.out.println("Number of times the most frequent occured integer is: " +maxOccurrences(list));
	}

}
Output:

Number of times the most frequent occured integer is: 4

 

0 0

Discussions

Post the discussion to improve the above solution.