-
沧海一幻觉
您可以使用Java Faker生成各种随机假数据。这是一个例子public static void main(String[] args) { Faker faker = new Faker(); System.out.println(faker.superhero().prefix()+faker.name().firstName()+faker.address().buildingNumber()); //MrSharon55747 //IllustriousDock6698 //CyborgDelilah207 //GeneralAllison01931 //RedWillard4366 //TheJarvis71802 }Maven 依赖:<dependency> <groupId>com.github.javafaker</groupId> <artifactId>javafaker</artifactId> <version>1.0.1</version></dependency>
-
扬帆大鱼
加载单独的形容词和名词数组。要生成 uid,请随机选择其中一个。大写。决定是否要附加一个整数以及应该附加一个随机数。连接并返回。import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.stream.Stream;public class UserIdGenerator { final List<String> adjectives = new ArrayList(); final List<String> nouns = new ArrayList(); final int minInt; final int maxInt; final Random random; public UserIdGenerator(Path adjectivesPath, Path nounsPath, int minInt, int maxInt) throws IOException { this.minInt = minInt; this.maxInt = maxInt; try (Stream<String> lines = Files.lines(adjectivesPath)) { lines.forEach(line -> adjectives.add(capitalize(line))); } try (Stream<String> lines = Files.lines(nounsPath)) { lines.forEach(line -> nouns.add(capitalize(line))); } this.random = new Random(); } private static String capitalize(String s) { return Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase(); } public String generate() { StringBuilder sb = new StringBuilder() .append(adjectives.get(random.nextInt(adjectives.size()))) .append(nouns.get(random.nextInt(nouns.size()))); int i = random.nextInt(maxInt); if (i >= minInt) { sb.append(i - minInt); } return sb.toString(); } public static void main(String [] args) throws IOException { UserIdGenerator userIdGenerator = new UserIdGenerator( Paths.get("28K adjectives.txt"), Paths.get("91K nouns.txt"), 20, 120); for (int i = 0; i < 100; ++i) { System.out.println(userIdGenerator.generate()); } }}有点乐趣:AncipitalBoxfuls67PlanePerfectionists0TrochaicSerinsUnroundedLightening29ExpectingRemittors37UnscorchedCrackbrains75Conscience-strickenStiles0MuddleheadedBaptistries7GauntLoan11IncompatibleImbalances33StipitateGabbards62AppreciatedAntihistamines41PipyAquanauts83BiosystematicMan-hours92NursedCornhusker15FlocculentCasketsUnshoedZestfulness70SulfuricVoyageur90ParticipialCulpableness27SunrayVidette43UllagedKidneyKhedivalSuperaltars74ArrayedConsorter77MagnetizedWhooper86TrimorphousDiscographers59HolsteredBola89AnagogicalLinacs19UnhumbledFlush99IrritableSuccourerMultispiralMetallurgy2SlitheringBelize8BarkierStimy45Bull-nosedGlossa45UnbiasedProscriptions44BilgierBlackburn7ScarabaeoidIrreality98SolidaryMeningiomas1UnciformSwell5WhateverTe-hees14ConsummatedYou'llBabblingVintnersControlledTergiversations4Rock-bottomConstructers77UltraistLummoxesExpectableMicrohenry65DecentralizedThriller51SaccharicMisanthropes26AnatropousMoldwarp20VelvetyLowlanderMelanousHideawayPromotiveDodecaphonism3AdriaticRebuttersInboundEscallops7RelishableSapotas74UnjaundicedDichromat71BloodshotAbuser63VibrativeKeltic86VeloceBugbear30UnclassifiedSeine-maritimeMetonymicalVenturousness36StemmedHurcheon6RefreshingBaggagesExpressibleOmens74KookiestSegments33AdmonishingNewsdealerSchoolgirlishKeitloas45DisgustfulStrangling9NoduloseGarnishesSeaworthyMurphy30ProximoAcromion13DisciplinalTransposition74UnveiledDissolutions60PrivilegedPorphyrin24PetitCommonage79UnrepugnantBwana33StatelierSordidnessIsorhythmicTulipomania97DeterministicAbstractness85IntercrossedTestudosWolfishOhms4NimbleTelemeter61PerthiticExpertises31WorshipfulHumanness15NiobeanDecumbency57PtolemaicGodspeedDiagonalMultistoreyBrawlingEglantines60SynclasticWalnuts64FibroticMordant28FibrilloseGemels66MitigativeDredger10ConfigurationalOberland67PrerogativeDoits96BoswellianSandman39CantharidalEpanodos23GrippingOracleSoft-coverDeveloping54AdjuratorySilas31MesozoicNorthmanWinterTraveling22
-
四季花海
组合以下解决方案来生成字母数字字符串,即使用 Java Faker 库生成名称,生成随机整数(解决方案取决于您使用的 java 版本)并组合字符串来构建字母数字字符串。
-
繁花如伊
试试这个public class UserNameGenerator { public static void main(String[] args) { for (int index = 0; index < 10; index++) { System.out.println("Generate: "+ getUserText(null)); } } /** * this generates a random username * @param somePseudoName it shall be used in username if provided * @return */ private static String getUserText(String somePseudoName) { String[] nameArray = new String[]{"hello", "world", "someday", "mltr", "coldplay"}; String userName = ""; if (somePseudoName != null && somePseudoName.length() > 0) { userName = somePseudoName; } else { userName = nameArray[new Random().nextInt(nameArray.length)]; } return userName + getRandomNumber(); } /** * this shall create a random number * @return a number text */ private static String getRandomNumber() { StringBuilder numberText = new StringBuilder(); int[] numbersArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int totalNumbers = new Random().nextInt(3); for (int index = 0; index < totalNumbers; index++) { numberText.append(numbersArray[new Random().nextInt(numbersArray.length)]); } return numberText.toString(); }}输出Generate: hello8Generate: mltrGenerate: someday4Generate: coldplay22Generate: worldGenerate: worldGenerate: coldplay79Generate: worldGenerate: coldplayGenerate: coldplay15