我就废话不多说了,大家还是直接看代码吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
/** * 从list中随机抽取元素 * * @param list * @param n * @return void * @throws * @Title: createRandomList * @Description: TODO */ 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, "" ); System.out.println(random + "===========" + list.get(random)); listNew.add(list.get(random)); } } return listNew; } } |
扩展:
截取list
list.subList(0, 2);
补充知识:java list随机打乱顺序
通过 Collections.shuffle(list)来打乱顺序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
List<String> list = new ArrayList<String>(); list.add( "mjb" ); list.add( "hh" ); list.add( "lw" ); list.add( "pqj" ); list.add( "hj" ); System.out.println( "前:" ); for ( int i= 0 ;i<list.size();i++){ System.out.print(list.get(i)+ " " ); } System.out.println( "" ); System.out.println( "后:" ); Collections.shuffle(list); for ( int i= 0 ;i<list.size();i++){ System.out.print(list.get(i)+ " " ); } |
以上这篇java list随机抽取元素的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u013939884/article/details/72364761