java list随机抽取元素的案例
我就废话不多说了,大家还是直接看代码吧~
/** * 从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)来打乱顺序
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随机抽取元素的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)