0

What's the most efficient way to generate "meaningful" usernames (alphanumerical strings) using Java?

Usernames in this format:

LastSamurai33
DarkLord96
FallenAngel
IceQueen
LadyPhantom666
DarkSun

Thank you for your time.

Man
  • 7
  • 1
  • 3
  • 4
    Dictionary to pick random words, random number generator to add numbers? – Elliott Frisch Sep 13 '19 at 03:51
  • 1
    The duplicate police have been a bit too aggressive imo. This question is quite different from the one cited as a dupe. – Gene Sep 13 '19 at 04:58
  • Funny thing. New day, new user, exact same list of examples ( https://stackoverflow.com/questions/57913370/generate-usernames-using-java ). And please note: this community isn't intended as code writing service. Instead of going "here are my requirements, it would be much better to start yourself. Try something, and when you are stuck, you are welcome to ask for help with that specific problem. But "please tell me the most efficient way to solve this thing", as said: not exactly appreciated. – GhostCat Sep 13 '19 at 05:22

4 Answers4

5

You can use Java Faker to generate wide range of random fake data.

Here's an example

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 :

<dependency>
    <groupId>com.github.javafaker</groupId>
    <artifactId>javafaker</artifactId>
    <version>1.0.1</version>
</dependency>
Ken de Guzman
  • 2,790
  • 1
  • 19
  • 33
  • Good answer, but does it answer the OP's question *What's the most efficient way to generate "meaningful" usernames* - Is this the most efficient way? – Scary Wombat Sep 13 '19 at 04:42
  • @GhostCat - My comment was tongue-in-cheek, actually think this was a good answer, even similar to that in the linked duplicate ;-) – Scary Wombat Sep 13 '19 at 05:13
1

Get some handy files here. Load separate arrays of adjectives and nouns. To generate a uid, randomly pick one of each. Capitalize. Decide if you want to attach an integer and what that should be with one more random number. Concatenate and return.

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());
    }
  }
}

Kind of fun:

AncipitalBoxfuls67
PlanePerfectionists0
TrochaicSerins
UnroundedLightening29
ExpectingRemittors37
UnscorchedCrackbrains75
Conscience-strickenStiles0
MuddleheadedBaptistries7
GauntLoan11
IncompatibleImbalances33
StipitateGabbards62
AppreciatedAntihistamines41
PipyAquanauts83
BiosystematicMan-hours92
NursedCornhusker15
FlocculentCaskets
UnshoedZestfulness70
SulfuricVoyageur90
ParticipialCulpableness27
SunrayVidette43
UllagedKidney
KhedivalSuperaltars74
ArrayedConsorter77
MagnetizedWhooper86
TrimorphousDiscographers59
HolsteredBola89
AnagogicalLinacs19
UnhumbledFlush99
IrritableSuccourer
MultispiralMetallurgy2
SlitheringBelize8
BarkierStimy45
Bull-nosedGlossa45
UnbiasedProscriptions44
BilgierBlackburn7
ScarabaeoidIrreality98
SolidaryMeningiomas1
UnciformSwell5
WhateverTe-hees14
ConsummatedYou'll
BabblingVintners
ControlledTergiversations4
Rock-bottomConstructers77
UltraistLummoxes
ExpectableMicrohenry65
DecentralizedThriller51
SaccharicMisanthropes26
AnatropousMoldwarp20
VelvetyLowlander
MelanousHideaway
PromotiveDodecaphonism3
AdriaticRebutters
InboundEscallops7
RelishableSapotas74
UnjaundicedDichromat71
BloodshotAbuser63
VibrativeKeltic86
VeloceBugbear30
UnclassifiedSeine-maritime
MetonymicalVenturousness36
StemmedHurcheon6
RefreshingBaggages
ExpressibleOmens74
KookiestSegments33
AdmonishingNewsdealer
SchoolgirlishKeitloas45
DisgustfulStrangling9
NoduloseGarnishes
SeaworthyMurphy30
ProximoAcromion13
DisciplinalTransposition74
UnveiledDissolutions60
PrivilegedPorphyrin24
PetitCommonage79
UnrepugnantBwana33
StatelierSordidness
IsorhythmicTulipomania97
DeterministicAbstractness85
IntercrossedTestudos
WolfishOhms4
NimbleTelemeter61
PerthiticExpertises31
WorshipfulHumanness15
NiobeanDecumbency57
PtolemaicGodspeed
DiagonalMultistorey
BrawlingEglantines60
SynclasticWalnuts64
FibroticMordant28
FibrilloseGemels66
MitigativeDredger10
ConfigurationalOberland67
PrerogativeDoits96
BoswellianSandman39
CantharidalEpanodos23
GrippingOracle
Soft-coverDeveloping54
AdjuratorySilas31
MesozoicNorthman
WinterTraveling22
Gene
  • 46,253
  • 4
  • 58
  • 96
  • Reminds on that other website where people get asked to build their porn star name, by combining the color of their current underwear with their most famous dish.... – GhostCat Sep 13 '19 at 05:23
0

Combine below solutions to generate alphanumerical strings, that is generate name using Java Faker Library, generate a random integer (solution depends on the java version you are using) and combine the strings to build the alphanumeric string.

Java: Randomly generate distinct names

How do I generate random integers within a specific range in Java?

Nevin
  • 769
  • 1
  • 11
  • 26
0

Try this out

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();
    }
}

output

Generate: hello8
Generate: mltr
Generate: someday4
Generate: coldplay22
Generate: world
Generate: world
Generate: coldplay79
Generate: world
Generate: coldplay
Generate: coldplay15
Pankaj Nimgade
  • 4,529
  • 3
  • 20
  • 30