java list随机抽取元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013939884/article/details/72364761
/**
     * 从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);

猜你喜欢

转载自blog.csdn.net/u013939884/article/details/72364761
今日推荐