How to generate a random alpha-numeric string

前端 未结 30 2562
忘掉有多难
忘掉有多难 2020-11-21 05:38

I\'ve been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifie

30条回答
  •  盖世英雄少女心
    2020-11-21 06:07

    I don't really like any of these answers regarding a "simple" solution :S

    I would go for a simple ;), pure Java, one liner (entropy is based on random string length and the given character set):

    public String randomString(int length, String characterSet) {
        return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int q = 0; q < 5; q++) {
            System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
        }
    }
    

    Or (a bit more readable old way)

    public String randomString(int length, String characterSet) {
        StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed
        for (int i = 0; i < length; i++) {
            int randomInt = new SecureRandom().nextInt(characterSet.length());
            sb.append(characterSet.substring(randomInt, randomInt + 1));
        }
        return sb.toString();
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int q = 0; q < 5; q++) {
            System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
        }
    }
    

    But on the other hand you could also go with UUID which has a pretty good entropy:

    UUID.randomUUID().toString().replace("-", "")
    

提交回复
热议问题