JAVA 实现加权轮询算法:有权重,按权重轮询,无权重随机分配

 private static PayMode random(List payModes) {
        int size = payModes.size();
        if (size == 1) {
            return payModes.get(0);
        }
        Map weightedPolling = new HashMap<>();
        for (PayMode payMode : payModes) {
            int weight = payMode.getWeight();
            if (weight > 0) {
                weightedPolling.put(payMode.getChnlScene().getChannelCode(), payMode);
            }
        }
        //无权重,随机
        if (weightedPolling.isEmpty()) {
            int index = new Random().nextInt(size);
            return payModes.get(index);
        }
        //有权重,按权重
        Set keySet = weightedPolling.keySet();
        ArrayList data = new ArrayList<>();
        for (String key : keySet) {
            int weight = weightedPolling.get(key).getWeight();
            for (int i = 0; i < weight; i++) {
                data.add(key);
            }
        }
        int index = new Random().nextInt(data.size());
        return weightedPolling.get(data.get(index));
    }

你可能感兴趣的:(windows,服务器,linux,java)