Home Java javaTutorial Introduction to how to generate a random string array in Java

Introduction to how to generate a random string array in Java

Aug 10, 2017 am 09:59 AM
java string random

This article mainly introduces the relevant information about Java's detailed examples of generating random string arrays. It mainly uses the Collections.sort() method to sort the List of generic Strings. Friends who need it can refer to it

Java Detailed Example of Generating a Random String Array

Use the Collections.sort() method to sort a List whose generic type is String. Specific requirements:

1. After creating List, add ten random strings to it
2. The length of each string is a random integer within 10
3. Each Each character of the string is a randomly generated character, and the characters can overlap
4. Each random string cannot be repeated

The knowledge involved is: String, StringBuffer, ListArray, Generics, Collections.sort, foreach, Random and other related knowledge can be regarded as a relatively good practice in the JAVA learning process.

1. Randomly generate a character

1.1 First store all letters and numbers 0-9 in a string for subsequent use.


String str = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStT
       uUvVwWxXyYzZ0123456789";
Copy after login

1.2 To satisfy the randomness, create a Random object and use the nextInt(str.length) method to generate a 0 — str.length random number.


Random random = new Random();
int index = random.nextInt(str.length());
Copy after login

1.3 Then use the random number generated above as the index of the str string to retrieve the corresponding character, and randomly generate a character


char c = str.charAt(index);
Copy after login

2. Generate a random string with a length within 10

2.1 Because it is within 10 and meets randomness, here Use the Math.random() function, whose return value is a random Double type number from 0.0 to 1.0


StringBuffer stringBuffer = new StringBuffer();
//确定字符串长度
int stringLength = (int) (Math.random()*10);
Copy after login

2.2 Now the length of the string can be confirmed, and Generate random characters, and then use the for loop to generate a random string with a length of less than 10


for (int j = 0; j < stringLength; j++) {
  int index = random.nextInt(str.length());
  char c = str.charAt(index);
  stringBuffer.append(c);  
 }
//将StringBuffer转换为String类型的字符串
String string = stringBuffer.toString();
Copy after login

3. Generate 10 Random string

3.1 After the above two steps, and then nesting a for loop outside, 10 random strings can be generated

4. Create a ListArray collection to store 10 random strings

4.1 Create a String type collection, this step should be completed simultaneously with Step 3


List<String> listString = new ArrayList<String>();
Copy after login

4.2 Add a string generated each time to the set. Pay attention to using the Contains() method of the set to determine whether the same string already exists in the set (although the probability is very small).


//判断当前的list容器中是否已有刚生成的字符串,满足每条字符串不可重复性
if(!(listString.contains(stringBuffer.toString()))){
   listString.add(stringBuffer.toString());
 }else {
   //i-- 如果不满足则重新生成
  i--;
 }
Copy after login

5 Finally sort the collection

5.1 Call the Collections.sort() method to sort the collection. The rules are as follows:

  • principle from left to right, and 0-9

  • number priority principle, and A-Z

  • Capital letters take precedence, and a-z

##Total code


import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class RandomString {

  public static void main(String[] args) {
    List strList = randomString();
    System.out.println("------随机生成的10条字符串-------");
    for (String string : strList) {
      System.out.println(string);
    }
    System.out.println("------------排序后------------");
    Collections.sort(strList);
    for (String string : strList) {
      System.out.println(string);
    }  
  }
  public static List randomString(){
    //将所有的大小写字母和0-9数字存入字符串中
    String str = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789";
    Random random = new Random();
    List<String> listString = new ArrayList<String>();
    String strArray[ ] = new String[10];
    //生成10条长度为1-10的随机字符串
    for (int i = 0; i < 10; i++) {
      StringBuffer stringBuffer = new StringBuffer();
      //确定字符串长度
      int stringLength = (int) (Math.random()*10);
       for (int j = 0; j < stringLength; j++) {
         //先随机生成初始定义的字符串 str 的某个索引,以获取相应的字符
        int index = random.nextInt(str.length());
        char c = str.charAt(index);
        stringBuffer.append(c);  
       }
       //判断当前的list容器中是否已有刚生成的字符串,满足每条字符串不可重复性
       if (!(listString.contains(stringBuffer.toString()))) {
         listString.add(stringBuffer.toString());
      }else {
        i--;
      }

    }
    return listString;
  }
}
Copy after login
The output answer is not unique

The above is the detailed content of Introduction to how to generate a random string array in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

See all articles