I am a beginner in Java and have the following issue.
How can I generate 5 random strings and add them to a Set
?
I am a beginner in Java and have the following issue.
How can I generate 5 random strings and add them to a Set
?
First, let's create the set:
Set<String> set = new HashSet<>();
Now, let's generate 5 random strings. There are many ways to do this, here is an answer about it. But since you did not ask for a specific length, let's proceed with this:
String randomStr = Long.toHexString(Double.doubleToLongBits(Math.random()));
Now, let's repeat the random generation 5 times:
for (int i = 0; i < 5; i++) {
set.add(Long.toHexString(Double.doubleToLongBits(Math.random())));
}
Now, the problem is that this does not guarantee the set will have 5 random strings, as we may have similar ones. To ensure that, we should do:
while (set.size() < 5) {
set.add(Long.toHexString(Double.doubleToLongBits(Math.random())));
}
The code above will continue generating random strings until the set contains at least 5. I'm not checking if it already contains the string because a Set, by definition, contains no duplicate elements. So, adding a duplicate won't increase the size.
You can do something like
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
Random random = new Random();
while (set.size() != 5) {
set.add(String.valueOf((char) (65 + random.nextInt(26))));
}
System.out.println(set);
}
}
A sample run:
[D, X, L, M, N]
Notes:
Random.nextInt(n)
generates an int
from 0 to n-1 where n
is an int
. Therefore, 65 + random.nextInt(26))
will generate a number from 65
to 90
.String.valueOf(c)
converts c
into a String
where c
is a char
.A
is 65
and that of Z
is 90
. So, ((char)65)
will be printed as A
.You can use UUID values for your random strings.
Set<String> strings = IntStream.range(0, 5).boxed()
.map(i -> UUID.randomUUID().toString())
.collect(Collectors.toSet());
Output:
[174686cc-f1e6-4532-944f-de5a85fa5979, 0151b604-93fa-41cf-8ca8-e872c29e261f, 030c6524-c8cb-4c32-a17b-6189a3a167d5, 3e99e7fd-f143-4af6-bcfc-9b968e9397c9, 11099e22-3c05-45e6-b989-2a3c62acaa15]
This example uses the number values of Unicode Characters to create a string, the Java.util.Random class is used to randomly generate a number:
public static void main(String args[]) {
Set<String> randomStrings = new HashSet<>();//create the set
Random random = new Random(); //this creates a random number
for(int i=0;i<5;i++) { //loop 5 times
String generatedString = random.ints(60, 122)//(min value, max value)
.limit(10) //sets the string length to 10 characters
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
randomStrings.add(generatedString); //add the generatedString to the Set
}
//print contents of the Set
for(String s: randomStrings) {
System.out.println(s);
}
}
pflmmE[jCu
ogofehE<XS
BFbqtHnE_O
Qvu@IDJcI=
Al>BvaLZ@[
Here is one solution (out of many possibilities). Note that this could be condensed into a few statements but then it would be difficult to explain with comments. First, let's get the easiest one done.
Random r = new Random(23);
Set<String> stringSet = new HashSet<>();
for (int i = 0; i < 5; i++) {
stringSet.add(Integer.toString(r.nextInt()));
}
stringSet.forEach(System.out::println);
Yep! Numbers have been converted to Strings. You didn't specify what type of strings.
Moving on...
Random r = new Random(23);
Set<String> stringSet = new HashSet<>();
for (int i = 0; i < 5; i++) {
// use a Stringbuilder to build it.
StringBuilder sb = new StringBuilder();
// length of string between 6 and 10 inclusive
int len = r.nextInt(5)+6;
// now build the string
while (len-- > 0) {
// generate a character from 'a' to 'z' inclusive
char c = (char)(r.nextInt(26) + 'a');
sb.append(c);
}
// and it to the set
stringSet.add(sb.toString());
}
// print them.
for (String s : stringSet) {
System.out.println(s);
}
This run printed
sefmjkzket
qfjklm
dxocur
mldkzcmv
ivqrynsspu
Your output could be different (they are random).
Note that the building of the string uses integers from 0 to 25 inclusive. Since the lower case letters are sequential, you get a
to z
by just adding a
to each number. One could also just index randomly into a string of letters like so:
String alphabet = "abcdefghijlmnopqrstuvwxyz";
index = r.random(26); //0 to 25
char c =alphabet.charAt(index);
As was stated, there are many ways to do this.
Here's a final demo using Streams. The strings are of a different nature.
String alphabet = "abcdefghijlmnopqrstuvwxyz";
Set<String> strings = Stream.generate(() -> 1)
.map(z -> alphabet.substring(r.nextInt(5),
r.nextInt(10) + 10))
.distinct().limit(5).collect(Collectors.toSet());
strings.forEach(System.out::println);
Print them
cdefghijl
abcdefghij
defghijlmnopqrs
cdefghij
cdefghijlmnopqrs
The solution with using alphabet:
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int stringLength = 10;
Set<String> strings = IntStream.range(0, 5)
.mapToObj(i -> IntStream.range(0, stringLength)
.mapToObj(j -> Character.toString(alphabet.charAt(new Random().nextInt(alphabet.length()))))
.collect(joining()))
.collect(toSet());
Output:
[XBZPISNKHR, EBAGPRHQNX, GOCZEBGRFC, YRTQZFQNQJ, DVSUXWEITU]
I don't know why you need to make random strings but I don't think it'll be easy tho I've never tried. Also I don't fully know what you mean by a set but I think you mean combine the strings to make a sentence? If that's the case just do this.
String str = "blah ";
String str2 = "ughhh ";
String str3 = "pshh ";
String together = str + str2 + str3;
System.out.println(together);
output
blah ughhh pshh