Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.Collection;

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

public class Main {
    /** 
     * @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();
    }
}