All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jelastic.api.core.utils.CollectionUtils Maven / Gradle / Ivy

The newest version!
/*Server class MD5: b012e11a957f142bf2aa261cd1571a1c*/
package com.jelastic.api.core.utils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @name Jelastic API Client
 * @version 8.11.2
 * @copyright Jelastic, Inc.
 */
public class CollectionUtils {

    public static boolean isEmpty(Collection coll) {
        return (coll == null || coll.isEmpty());
    }

    public static  Predicate distinctByKey(Function keyExtractor) {
        Set seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    public static  T getMostFrequentElement(Collection collection) {
        Map map = new HashMap<>();
        for (T t : collection) {
            Integer val = map.get(t);
            map.put(t, val == null ? 1 : val + 1);
        }
        Map.Entry max = null;
        for (Map.Entry e : map.entrySet()) {
            if (max == null || e.getValue() > max.getValue()) {
                max = e;
            }
        }
        return max.getKey();
    }
}