most Occurring Element in Collection - Java java.util

Java examples for java.util:Collection Element

Description

most Occurring Element in Collection

Demo Code


//package com.java2s;
import java.util.Collection;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] argv) {
        Collection list = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(mostOccurringElement(list));
    }//from   w w  w  . ja  va 2  s  .  c  o  m

    /** 
     * @see list argument list
     * @return the most occurring element in list; when more elements occur equally
     * often, the earliest occurring element is returned.
     **/
    public static <T> T mostOccurringElement(Collection<T> list) {
        Map<T, Integer> map = new HashMap<>();

        for (T t : list) {
            Integer val = map.get(t);
            map.put(t, val == null ? 1 : val + 1);
        }

        Map.Entry<T, Integer> max = null;

        for (Map.Entry<T, Integer> e : map.entrySet()) {
            if (max == null || e.getValue() > max.getValue()) {
                max = e;
            }
        }
        return max == null ? null : max.getKey();
    }
}

Related Tutorials