/** * * @param objects: A Map containing the objects to choose from, where the keys represent the objects and the values represent their respective weights. * @return Returns a randomly selected element from a Map, with selection probabilities proportional to each element's weight. * @param A randomly selected element from the Map, or null if the Map is empty. */ public static T getRandomWeightedElement(Map objects) { double sum = objects.values().stream().mapToDouble(Number::doubleValue).sum(); for (T item : objects.keySet()) { random -= objects.get(item).doubleValue(); if (random <= 0.0d) { return item; } } return null; }