//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博客
