Java笔试:生成100W条随机字符串(有规律格式),然后随机获取100个不重复的,排序,输出生成文件
时间: 2024-03-05 18:51:16 浏览: 118
好的,针对您的问题,我可以提供以下思路:
1. 生成100W条随机字符串
由于有规律格式,我们可以考虑使用循环生成字符串。假设规律格式为:字母+数字+字母+数字,共8位。
```
List<String> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 1000000; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 8; j++) {
if (j % 2 == 0) { // 字母
char c = (char) (random.nextInt(26) + 'A');
sb.append(c);
} else { // 数字
int num = random.nextInt(10);
sb.append(num);
}
}
list.add(sb.toString());
}
```
2. 随机获取100个不重复的字符串
使用 Collections.shuffle 方法打乱顺序,然后取前100个即可。
```
Collections.shuffle(list);
List<String> randomList = list.subList(0, 100);
```
3. 排序并输出到文件
将随机取得的100个字符串排序,然后输出到文件中。
```
Collections.sort(randomList);
File file = new File("output.txt");
try (PrintWriter writer = new PrintWriter(file)) {
for (String str : randomList) {
writer.println(str);
}
}
```
完整代码如下:
```
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Test {
public static void main(String[] args) throws Exception {
List<String> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 1000000; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 8; j++) {
if (j % 2 == 0) { // 字母
char c = (char) (random.nextInt(26) + 'A');
sb.append(c);
} else { // 数字
int num = random.nextInt(10);
sb.append(num);
}
}
list.add(sb.toString());
}
Collections.shuffle(list);
List<String> randomList = list.subList(0, 100);
Collections.sort(randomList);
File file = new File("output.txt");
try (PrintWriter writer = new PrintWriter(file)) {
for (String str : randomList) {
writer.println(str);
}
}
}
}
```
阅读全文