个人随笔
目录
工具类:Java实现传入一个list返回一个打乱顺序的list
2021-03-08 18:37:53

场景

有时候我们需要随机获取list中的数据来做判断,判断不通过再随机取下一个数据,如果每次都随机取获取太麻烦了,我们可以直接将list中的数据随机打乱,然后返回list就可以循环该list来处理就可以了。

代码实现

  1. /**
  2. * suibibk.com
  3. * @author 小林同学
  4. *
  5. */
  6. public class RandomList {
  7. /**
  8. * 输入一个list,返回一个打乱顺序的list
  9. * @param list
  10. * @return
  11. */
  12. public static List<String> getRandomList(List<String> list){
  13. if(list==null||list.size()==0) {
  14. return null;
  15. }
  16. //1、建立一个随机数生成器对象
  17. SecureRandom random = new SecureRandom();
  18. //2、建立一个乱序的对象
  19. List<String> result = new ArrayList<String>();
  20. boolean flag = true;
  21. int size = 0;
  22. while(flag) {
  23. size = list.size();
  24. //随机生成一个下标
  25. int index = random.nextInt(size);
  26. //将内容添加入list中
  27. result.add(list.get(index));
  28. //从原有的list中移除
  29. list.remove(index);
  30. if(list.size()==0) {
  31. flag=false;
  32. }
  33. }
  34. return result;
  35. }
  36. public static void main(String[] args) {
  37. for (int i=0;i<100;i++) {
  38. //不能用这个方法获取list,这个方法获取的是AbstractList
  39. //List<String> list = Arrays.asList(str);
  40. List<String> list = new ArrayList<>();
  41. list.add("1");
  42. list.add("2");
  43. list.add("3");
  44. list.add("4");
  45. list.add("5");
  46. List<String> result = getRandomList(list);
  47. System.out.println(result);
  48. }
  49. }
  50. }

测试结果

  1. ...
  2. [3, 5, 4, 2, 1]
  3. [3, 2, 5, 1, 4]
  4. [4, 5, 2, 1, 3]
  5. [2, 3, 4, 1, 5]
  6. [5, 1, 4, 2, 3]
  7. [2, 1, 3, 4, 5]
  8. ...
 478

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2