快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

通过数组获取唯一指定几个数据

1、通过数组内容获取想要数组中几个唯一数据

  @Test
    public void t74() {
        String[] arrStr = {"2092314", "2092313", "2078103", "588506", "353867", "337220", "337221", "337233", "337189", "318945"};
        HashSet getrunmber = getrunmber(1, arrStr);
        getrunmber.forEach(m -> Log.info(m));

    }

    /**
     * 根据数组长,返回唯一相应数据
     * @param n
     * @param str
     * @return
     */
    public HashSet getrunmber(int n, String[] str) {
        Random random = new Random();
        HashSet setlist = new HashSet<>();
        if (n <= str.length && n != 0 && str.length != 0 && str != null) {
            while (setlist.size() < n) {
                int c = random.nextInt(str.length);
                setlist.add(str[c]);
            }
        } else {
            Log.info("获取的数据大于String数据的长度");
            return null;
        }
        return setlist;
    }

2通过文件读取获取指定唯一数据


    /**
     * 通过读取文件或指定唯一数据
     * @param n
     * @param str
     * @return
     */
    public HashSet getrunmber(int n, String str) {
        Random random = new Random();
        HashSet setlist = new HashSet<>();
        ArrayList list = fileReaderr(str);
        if (n <= list.size() && n != 0 && list.size() != 0 && str != null) {
            while (setlist.size() < n) {
                int c = random.nextInt(list.size());
                setlist.add(list.get(n));
            }
        } else {
            Log.info("获取的数据大于String数据的长度");
            return null;
        }
        return setlist;
    }

 /**
     * 通过读取文件内容
     * @param file
     * @return list
     */
    public static ArrayList fileReaderr(String file) {
        BufferedReader bufferedReader = null;
        String len = null;
        ArrayList list = new ArrayList<>();
        File numberpath = new File(file);
        if (!numberpath.exists()) {
            Log.info("文件不存在");
            return null;
        }
        try {
            bufferedReader = new BufferedReader(new FileReader(numberpath));
            while ((len = bufferedReader.readLine()) != null) {
                list.add(len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

本文名称:通过数组获取唯一指定几个数据
浏览地址:http://6mz.cn/article/gessih.html

其他资讯