Finding the most popular element in Java


import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;

/**
 * Here the algorithm is
 * 1. Iterate through the array and put the element as key and count as value in HashMap.
 * 2. While adding into the HashMap check if the key already exist or not
 * 		a) if exist increment the count and add it.
 * 		b) if not exist add element with count 0.
 * 3. Then get the Entry with max value.
 * 		a) Collections.max() Returns the maximum element of the given collection,
 * 		   according to the natural ordering of its elements.(you need to pass the comparator if you want your own logic)
 *
 */

public class PopularEmelementInArrayFinder {

	public static void main(String[] args) {

		int [] array = {1,5,8,4,5,8,4,5,8,8,5,8,5,8,5,4,1,4,2,5,2,6,8,4,2,5,8,2};
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

		for (int i = 0; i < array.length; i++) {
			Integer count = map.get(array[i]);
			map.put(array[i], count != null ? count+1 :0);
		}

		 Entry<Integer,Integer> entry= Collections.max(map.entrySet() , new Comparator<Entry<Integer, Integer>>() {

			public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
				return  o1.getValue().compareTo(o2.getValue());
			}
		});

		 int popularValueInArray = entry.getKey();
		System.out.println(map);
		System.out.println("popular value in given array is "+ popularValueInArray);

	}
}

Advertisements

About sivateja

I am a professional graduate..I am passionate about Latest Technology.
This entry was posted in Programing questions, Uncategorized and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s