RandomUtil.java 1.5 KB

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