package com.maya.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class RandomSelect { public static void main(String[] args) { String[] names = { "郇", "王", "焦", "刘", "尹", "吕", "巩", "董", "白", "朱", "封", "郭", "班", "杨"}; List<List<String>> gl = getGroup(names, 3); if(gl != null) { for (List<String> l : gl) { System.out.println(l); } } } /** * 获取随机数 */ public static int getRandom(int i) { Random r = new Random(); return r.nextInt(i); } /** * 进行分组 els 需要进行分组的成员 groups 需要分成几组 */ public static List<List<String>> getGroup(String[] els, int groups) { // 判断验证 if (els.length < (groups * 2)) { System.out.println("分组数过多! 最多只能分" + (els.length / 2) + "组"); return null; } if (groups == 1) { System.out.println("分组数不能为1组"); return null; } // 数据源的list List<String> list = new ArrayList<String>(); // 作为结果返回的list List<List<String>> groupsList = new ArrayList<List<String>>(); // List<Map<String, String>> groupsList = new ArrayList<List<String>>(); // 往数据源里面添加数据 for (int i = 0; i < els.length; i++) { list.add(els[i]); } // 随机打乱一下顺序 Collections.shuffle(list); // 计算一下每组多少人 int peoples = els.length / groups; // 分组开始 for (int i = 0; i < groups; i++) { List<String> group = new ArrayList<String>(); for (int j = 0; j < peoples; j++) { int random = getRandom(list.size()); group.add(list.get(random)); list.remove(random); } groupsList.add(group); } // 最后剩下的人再重新分配一遍 for (int i = 0; i < list.size(); i++) { groupsList.get(i).add(list.get(i)); } return groupsList; } }
这个随即分组的思想可以在很多地方运用