java list随机抽取元素

来源:互联网 发布:windows.hlp官方下载 编辑:程序博客网 时间:2024/06/05 11:34
/**     * 从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);
原创粉丝点击