1. package com.atguigu.msmservice.util;
    2. import java.text.DecimalFormat;
    3. import java.util.ArrayList;
    4. import java.util.HashMap;
    5. import java.util.List;
    6. import java.util.Random;
    7. /**
    8. * 获取随机数
    9. *
    10. * @author qianyi
    11. *
    12. */
    13. public class RandomUtil {
    14. private static final Random random = new Random();
    15. private static final DecimalFormat fourdf = new DecimalFormat("0000");
    16. private static final DecimalFormat sixdf = new DecimalFormat("000000");
    17. public static String getFourBitRandom() {
    18. return fourdf.format(random.nextInt(10000));
    19. }
    20. public static String getSixBitRandom() {
    21. return sixdf.format(random.nextInt(1000000));
    22. }
    23. /**
    24. * 给定数组,抽取n个数据
    25. * @param list
    26. * @param n
    27. * @return
    28. */
    29. public static ArrayList getRandom(List list, int n) {
    30. Random random = new Random();
    31. HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
    32. // 生成随机数字并存入HashMap
    33. for (int i = 0; i < list.size(); i++) {
    34. int number = random.nextInt(100) + 1;
    35. hashMap.put(number, i);
    36. }
    37. // 从HashMap导入数组
    38. Object[] robjs = hashMap.values().toArray();
    39. ArrayList r = new ArrayList();
    40. // 遍历数组并打印数据
    41. for (int i = 0; i < n; i++) {
    42. r.add(list.get((int) robjs[i]));
    43. System.out.print(list.get((int) robjs[i]) + "\t");
    44. }
    45. System.out.print("\n");
    46. return r;
    47. }
    48. }