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

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://myzitong.com/article/gessih.html