public class RandomStrCreator {
private static final String[] tmp = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };//,"+","/"
private static Random rand = new Random();
public static String createRandomStr(int i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i; j++) {
sb.append(tmp[rand.nextInt(tmp.length)]);
}
return sb.toString();
}
public static void main(String[] args) {
long currentTimeMillis = System.currentTimeMillis();
String str = createRandomStr(128);
System.out.println(str);
System.out.println(System.currentTimeMillis() - currentTimeMillis);
}
}
结果:
6DAcWg7ilbxbH0WLUWhSScHxSN7AZr065KobhOnB4tIqLNdtgHsA4uzGg91W2jEqfhWn8KjpcuRAHhkSjdSawjkUVefzqCQcTUMBPVe0psnutAHxSh74I1PJiWFkHVxl
0
增加:随机生成不重复数据:
复制代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class RandomStrCreator {
private static final String[] tmp = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };//,"+","/"
private static Random rand = new Random();
public static String createRandomStr(int i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i; j++) {
sb.append(tmp[rand.nextInt(tmp.length)]);
}
return sb.toString();
}
public static void main(String[] args) {
//Thread t2 = new Thread(() -> System.out.println("use lambda"));
//HashMap<String, String> map=new HashMap<String, String>();
/*long currentTimeMillis = System.currentTimeMillis();
String str = createRandomStr(128);
System.out.println(str);
System.out.println(System.currentTimeMillis() - currentTimeMillis);*/
List<Integer> diffNum = getDiffNum(6);
System.out.println(diffNum);
}
private static final Integer[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
/**
*
* #注意:Arrays.asList(arr)方法返回的list,不支持add,move操作 ,会报UnsupportedOperationException的错误
*/
public static List<Integer> getDiffNum(int i) {
List<Integer> rs = new ArrayList<>();
Integer[] numsTmp = nums.clone();
for (int j = 0; j < i; j++) {
int len = rand.nextInt(numsTmp.length);
int tN = numsTmp[len];
rs.add(tN);
List<Integer> asList = transferArrayToList(numsTmp);
asList.remove(len);
Integer[] intes =new Integer[asList.size()];
numsTmp = asList.toArray(intes);
}
rs.sort((a,b) -> a.compareTo(b));
return rs;
}
private static List<Integer> transferArrayToList(Integer[] array){
List<Integer> transferedList = new ArrayList<>();
Arrays.stream(array).forEach(arr -> transferedList.add(arr));
return transferedList;
}
}