//shuffle 打乱顺序 Collections.shuffle(list); //随机抽取1个值 System.out.println(list.get(0)); //随机抽取N个值 System.out.println(list.size() < N ? list : list.subList(0, N));
其他方案:
随机抽取1个值
public static void main(String[] args) { List<String> list = Arrays.asList("a","b","c"); int index = (int) (Math.random()* list.size()); System.out.println(list.get(index)); }
随机抽取N个值
private static List createRandomList(List list, int n) { // TODO Auto-generated method stub Map map = new HashMap(); List listNew = new ArrayList(); if (list.size() <= n) { return list; } else { while (map.size() < n) { int random = (int) (Math.random() * list.size()); if (!map.containsKey(random)) { map.put(random, ""); listNew.add(list.get(random)); } } return listNew; } }
参考博客:
1,java list随机抽取元素 - 小小的博客 - CSDN博客
https://blog.csdn.net/u013939884/article/details/72364761
2,Java List随机取值 - 只能永远把艰辛的劳动看作是生命的必要;即使没有收获的指望,也能心平气静的继续耕种. - CSDN博客