温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-15 15:40:22 来源:网络 阅读:342 作者:知止内明 栏目:编程语言

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

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

    }

    /**
     * 根据数组长,返回唯一相应数据
     * @param n
     * @param str
     * @return
     */
    public HashSet<String> getrunmber(int n, String[] str) {
        Random random = new Random();
        HashSet<String> 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<String> getrunmber(int n, String str) {
        Random random = new Random();
        HashSet<String> setlist = new HashSet<>();
        ArrayList<String> 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<String> fileReaderr(String file) {
        BufferedReader bufferedReader = null;
        String len = null;
        ArrayList<String> 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;
    }
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI