惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Spread Privacy
Spread Privacy
H
Hacker News: Front Page
PCI Perspectives
PCI Perspectives
Webroot Blog
Webroot Blog
罗磊的独立博客
H
Heimdal Security Blog
TaoSecurity Blog
TaoSecurity Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
Last Week in AI
Last Week in AI
美团技术团队
Help Net Security
Help Net Security
The Hacker News
The Hacker News
C
Cisco Blogs
T
The Blog of Author Tim Ferriss
J
Java Code Geeks
The Register - Security
The Register - Security
IT之家
IT之家
WordPress大学
WordPress大学
Jina AI
Jina AI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Help Net Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
NISL@THU
NISL@THU
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
B
Blog
T
Tenable Blog
博客园 - 三生石上(FineUI控件)
T
The Exploit Database - CXSecurity.com
S
Security Affairs
小众软件
小众软件
Hacker News: Ask HN
Hacker News: Ask HN
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
A
Arctic Wolf
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence

博客园 - VipSoft

Python 项目简单部署(Linux) MinerU - 将非结构化文档(PDF、图片、Office 文件等)转换为机器可读的 Markdown 和 JSON LangChain 入门 服务端部署-FastAPI LangChain 入门 LangSmith LangChain 入门 实战 - 食谱推荐 LangChain 入门 Memory 会话记忆 LangChain 入门 Tools 工具 LangChain 入门 Tools 工具 LangChain 入门 Prompts 提示词 LangChain 入门 Message 消息 LangChain 入门 Model 的初始化和调用 LangChain 入门 Agent 的基本运行机制 AI 0基础学习,名词解析 LangChain 和 LangGraph AI大模型知识体系 Dify — Workflow - 数据可视化 Dify — 连接MySQL配置 Dify — Chatflow - 数据库智能查询 Dify — Chatflow - 文档知识库 Dify — Agent 智能体 高安全券码、注册码生成 Dify — 文本生成应用 Dify — 聊天助手 -- 知识库 Windows 下 Docker 安装 Dify Ollama — 命令 Ollama — 为什么能够运行不同的模型 Ollama — 接口 Qwen — 自定义模型文件 Ollama Qwen — 安装测试 Ollama Windows 安装 & 指定安装目录 跟着AI学AI - 诊断结论信息抽取 - 批量处理脚本 跟着AI学AI - 诊断结论信息抽取 - 模型压缩与部署 跟着AI学AI - 诊断结论信息抽取 - 模型评估与调试 跟着AI学AI - 诊断结论信息抽取 - 模型训练 轻型民用无人驾驶航空器安全操控理论考试培训材料 FreeRedis Helper Windbg w3wp.DMP 内存分析 跟着AI学AI - 诊断结论信息抽取 - 数据增强 QQ 录屏软件 Java - 加权随机算法 - 示例 Java LoadBalanceUtil 负载均衡、轮询加权 SpringBoot 集成 IP2Region 获取IP地域信息 Windows 服务器和虚拟主机,创建.开头的文件夹 .well-known 跟着AI学AI - 诊断结论信息抽取 - 数据格式转换BERT训练格式 跟着AI学AI - 诊断结论信息抽取 - LabelStudio 标注 -- 结论标注 跟着AI学AI - 诊断结论信息抽取 - 学习路径 跟着AI学AI - UV 安装 数据标注工具 Label-Studio `VIRTUAL_ENV=venv` does not match the project environment 跟着AI学AI - 学习路径 - 命名实体识别(NER)和信息抽取(IE) 跟着AI学AI - 需要购买显卡吗? C# 无BOM的UTF-8编码 Vue ref reactive Vue - el-table 嵌套表 Spring `@Scheduled` 中这些参数的区别、组合和应用场景 Python 找出同步日志中的重复数据 Python - UV PyCharm 不能识别 .venv 的环境
Java - 加权随机算法--Demo
VipSoft · 2026-03-20 · via 博客园 - VipSoft

Java LoadBalanceUtil 负载均衡、轮询加权 https://www.cnblogs.com/vipsoft/p/19728820
Java - 加权随机算法 - 示例:https://www.cnblogs.com/vipsoft/p/19742349

A 权重 1 、B 权重 2 、C 权重 3
怎么能每次根据权重,做随机得到 A\B\C

我给你提供几种Java实现权重随机算法的方法:

方法一:数组扩展法(最简单)

import java.util.Random;

public class WeightRandom {
    private static final Random random = new Random();
    
    public static String getRandomByWeight() {
        // 权重:A(1), B(2), C(3)
        String[] items = {"A", "B", "C"};
        int[] weights = {1, 2, 3};
        
        // 计算总权重
        int totalWeight = 0;
        for (int weight : weights) {
            totalWeight += weight;
        }
        
        // 生成随机数
        int randomNum = random.nextInt(totalWeight); // 0-5
        
        // 根据权重选择
        if (randomNum < 1) {
            return "A";
        } else if (randomNum < 1 + 2) {
            return "B";
        } else {
            return "C";
        }
    }
    
    public static void main(String[] args) {
        // 测试100次,查看分布
        int aCount = 0, bCount = 0, cCount = 0;
        for (int i = 0; i < 100; i++) {
            String result = getRandomByWeight();
            switch (result) {
                case "A": aCount++; break;
                case "B": bCount++; break;
                case "C": cCount++; break;
            }
        }
        System.out.printf("A: %d次, B: %d次, C: %d次%n", aCount, bCount, cCount);
    }
}

方法二:通用工具类(推荐)

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class WeightRandomUtil<T> {
    private final List<WeightItem<T>> items = new ArrayList<>();
    private int totalWeight = 0;
    private final Random random = ThreadLocalRandom.current();
    
    public static class WeightItem<T> {
        T item;
        int weight;
        
        public WeightItem(T item, int weight) {
            this.item = item;
            this.weight = weight;
        }
    }
    
    public void addItem(T item, int weight) {
        items.add(new WeightItem<>(item, weight));
        totalWeight += weight;
    }
    
    public T next() {
        if (items.isEmpty() || totalWeight == 0) {
            return null;
        }
        
        int randomNum = random.nextInt(totalWeight);
        int currentWeight = 0;
        
        for (WeightItem<T> item : items) {
            currentWeight += item.weight;
            if (randomNum < currentWeight) {
                return item.item;
            }
        }
        
        return null; // 不应该到这里
    }
    
    public static void main(String[] args) {
        WeightRandomUtil<String> wr = new WeightRandomUtil<>();
        wr.addItem("A", 1);
        wr.addItem("B", 2);
        wr.addItem("C", 3);
        
        // 测试
        Map<String, Integer> countMap = new HashMap<>();
        for (int i = 0; i < 1000; i++) {
            String result = wr.next();
            countMap.merge(result, 1, Integer::sum);
        }
        
        System.out.println("测试结果:");
        countMap.forEach((k, v) -> 
            System.out.printf("%s: %d次 (占比 %.1f%%)%n", 
                k, v, v / 10.0));
    }
}

方法三:TreeMap实现(二分查找优化)

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class WeightRandomTreeMap<T> {
    private final TreeMap<Integer, T> weightMap = new TreeMap<>();
    private int totalWeight = 0;
    private final Random random = ThreadLocalRandom.current();
    
    public void addItem(T item, int weight) {
        totalWeight += weight;
        weightMap.put(totalWeight, item);
    }
    
    public T next() {
        if (weightMap.isEmpty()) {
            return null;
        }
        int randomNum = random.nextInt(totalWeight) + 1;
        Map.Entry<Integer, T> entry = weightMap.ceilingEntry(randomNum);
        return entry != null ? entry.getValue() : null;
    }
    
    public static void main(String[] args) {
        WeightRandomTreeMap<String> wr = new WeightRandomTreeMap<>();
        wr.addItem("A", 1);
        wr.addItem("B", 2);
        wr.addItem("C", 3);
        
        // 测试
        Map<String, Integer> countMap = new HashMap<>();
        for (int i = 0; i < 1000; i++) {
            String result = wr.next();
            countMap.merge(result, 1, Integer::sum);
        }
        
        System.out.println("测试结果:");
        countMap.forEach((k, v) -> 
            System.out.printf("%s: %d次 (占比 %.1f%%)%n", 
                k, v, v / 10.0));
    }
}

方法四:Apache Commons Math(第三方库)

如果项目中使用Apache Commons Math,可以更简洁:

import org.apache.commons.math3.distribution.EnumeratedDistribution;
import org.apache.commons.math3.util.Pair;

import java.util.ArrayList;
import java.util.List;

public class WeightRandomApache {
    public static void main(String[] args) {
        List<Pair<String, Double>> items = new ArrayList<>();
        items.add(new Pair<>("A", 1.0));
        items.add(new Pair<>("B", 2.0));
        items.add(new Pair<>("C", 3.0));
        
        EnumeratedDistribution<String> distribution = 
            new EnumeratedDistribution<>(items);
        
        // 测试
        for (int i = 0; i < 10; i++) {
            System.out.print(distribution.sample() + " ");
        }
    }
}

建议

  1. 简单场景:使用方法一,最直观
  2. 通用需求:使用方法二,可重用性好
  3. 大数据量:使用方法三(TreeMap),查找效率高(O(log n))
  4. 已有Apache Commons:使用方法四,代码最简洁

你的权重配置(A:1, B:2, C:3)意味着:

  • A的概率:1/6 ≈ 16.7%
  • B的概率:2/6 ≈ 33.3%
  • C的概率:3/6 = 50%