select Random value from a Map - Java java.util

Java examples for java.util:Map Value

Description

select Random value from a Map

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.Collection;
import java.util.Collections;

import java.util.List;
import java.util.Map;

public class Main {
    public static <K, V> List<V> selectRandom(Map<K, V> map, int size) {
        if (isNull(map)) {
            return null;
        }/*from w ww .  j  a v  a 2 s.  c o m*/
        List<V> values = valueToList(map);
        if (values.size() <= size) {
            return new ArrayList<V>(values);
        }
        Collections.shuffle(values);
        return values.subList(0, size);
    }

    public static boolean isNull(Collection<?> con) {
        if (con == null || con.isEmpty()) {
            return true;
        }
        return false;
    }

    public static boolean isNull(Object[] array) {
        if (array == null || array.length == 0) {
            return true;
        }
        return false;
    }

    public static boolean isNull(Map<?, ?> map) {
        if (map == null || map.isEmpty()) {
            return true;
        }
        return false;
    }

    public static <K, V> List<V> valueToList(Map<K, V> map) {
        if (isNotNull(map)) {
            return new ArrayList<V>(map.values());
        }
        return null;
    }

    public static boolean isNotNull(Object[] array) {
        return !isNull(array);
    }

    public static boolean isNotNull(Collection<?> con) {
        return !isNull(con);
    }

    public static boolean isNotNull(Map<?, ?> map) {
        return !isNull(map);
    }
}

Related Tutorials