// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

public class MajorityElementShort {
    public static void main(String[] args) {
        int[] numbersArray = { 2, 2, 1, 1, 1, 2, 2 };
        Optional<Entry<Integer,Long>> requiredElement = findMajorityElement(numbersArray);
        if (requiredElement.isPresent()) {
            System.out.printf("Majority element in array is %d with %d instances\n", requiredElement.get().getKey(), requiredElement.get().getValue());
        } else {
            System.out.println("No Majority element identified");
        }
    }
    public static Optional<Entry<Integer,Long>> findMajorityElement(int[] numbersArray) {
        return Arrays.stream(numbersArray).boxed()
                     .collect(Collectors.groupingBy(v -> v, LinkedHashMap::new, Collectors.counting()))
                     .entrySet().stream().sorted((e1,e2) -> (int)(e2.getValue() - e1.getValue()))
                     .findFirst();
    }
}
