zoukankan      html  css  js  c++  java
  • java中list或数组中随机子集工具类

    package com.example.demo.test;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Random;
    import java.util.concurrent.ThreadLocalRandom;

    /**
    * @author niunafei
    * @function
    * @email niunafei0315@163.com
    * @date 2018/12/23 下午1:17
    */
    public class RandomUtils {

    /**
    * 从list 中获取制定个数的子串
    *
    * @param tl
    * @param n
    * @param <T>
    * @return
    */
    public static <T> List randomSub(List<T> tl, int n) {
    int count = tl.size()>n?n:tl.size();
    Random r = ThreadLocalRandom.current();
    //避免修改原列表
    List<T> temp = new ArrayList<>(tl);
    //记录返回列表
    List<T> list = new ArrayList<>(count);
    for (int i=0;i<count;i++) {
    int t=r.nextInt(temp.size());
    list.add(temp.get(t));
    temp.remove(t);
    }
    return list;
    }


    /**
    * 数组中获取指定个数的子串
    * @param t
    * @param n
    * @param <T>
    * @return
    */
    public static <T>T[] randomSub(T[] t,int n){
    List<T> list=randomSub(Arrays.asList(t),n);
    return list.toArray(Arrays.copyOf(t,list.size()));
    }




    public static void main(String[] args){
    List<Integer> list =new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,0,12,35,46,54,1,2,3,45,6,7,89,0));
    System.out.println("原始:"+list);
    System.out.println("随机10"+randomSub(list,10));
    System.out.println("原始:"+list);
    Integer[] array={1,2,3,4,5,6,7,8,9,0,12,35,46,54,1,2,3,45,6,7,89,0};
    //使用Arrays.asList();将数组转为list
    System.out.println("原始数组"+Arrays.asList(array));
    System.out.println("数组随机10"+Arrays.asList(randomSub(array,10)));
    System.out.println("原始数组"+Arrays.asList(array));
    }
    }


    https://www.aliyun.com/acts/product-section-2019/new-users?userCode=q3tq2yrp
  • 相关阅读:
    ntohs, ntohl, htons,htonl的比较和详解【转】
    Device Tree 详解【转】
    浅析Linux DeviceTree【转】
    【spring boot】spring boot 拦截器
    【jQuery】jQuery/js 判断字符串是否JSON字符串
    【java】java中的 &= 和 |= 和 ^= 的区别
    zabbix创建触发器、action,发送报警邮件
    html iframe禁用右键
    mysql数据库mysqldump方式备份
    JDK8新特性
  • 原文地址:https://www.cnblogs.com/niunafei/p/10164940.html
Copyright © 2011-2022 走看看