How to generate a random alpha-numeric string

前端 未结 30 2559
忘掉有多难
忘掉有多难 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:00

    Here is the one-liner by AbacusUtil:

    String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())
    

    Random doesn't mean it must be unique. To get unique strings, use:

    N.uuid() // E.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.
    N.guid() // E.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'
    

提交回复
热议问题