最近有个同学说入参50万数据,出参10万不相同的随机数。怎么实现?
结果查看,控制台显示不全,于是调大就好了。
复制到vscode中查找哪些重复了:
代码想到两种写法,
package sample.entity;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class TestListNumber {
public static void main(String[] args) {
// long start = System.currentTimeMillis();
// List<Integer> lists = TestListNumber.getNumber(500000);
// long end = System.currentTimeMillis();
// System.out.println(lists.size()+"---"+(end-start)+"ms");
long start = System.currentTimeMillis();
Integer[] a = TestListNumber.getNumber2(500000);
long end = System.currentTimeMillis();
System.out.println("结果:"+a.length+"---"+(end-start)+"ms");
// for (int i = 0; i < a.length; i++) {
// System.out.println(a[i]);
// }
}
static Random r = new Random();
public static List<Integer> getNumber(int num){
List<Integer> out = new ArrayList<>();
int i=1;
int j=0;
while (i<=100000){
j = r.nextInt(num);
if(out.contains(j)){
continue;
}
out.add(j);
i++;
}
return out;
}
public static Integer[] getNumber2(int num){
Integer out[] = new Integer[100000];
int i=0;
int j=0;
out:while (i<100000){
j = r.nextInt(num);
out[i]=j;
//System.out.println((i+1)+"----"+out[i]);
for (int k = 0; k < i; k++) {
if (out[k] == out[i]) {
//System.out.println("重复----"+out[i]);
continue out;
}
}
i++;
}
return out;
}
}
明显,数组效率好。看还有什么更好的实现呢。
Java8新式写法
//粘贴一个java8的stream()串行写法,parallelStream()并行写法和传统for写法的处理时间对比
@Test
public void contextLoads() {
//初始化一个list
long first = new Date().getTime();
List<Student> list = new ArrayList<>();
for (int i = 1; i < 5000; i++) {
Student listToMap = new Student();
listToMap.setId(i);
listToMap.setName("name" + i);
listToMap.setAge(i + 20);
list.add(listToMap);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("传统所用时间" + (new Date().getTime() - first));
long startTime = new Date().getTime();
list.stream().forEach(f -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("串行所用时间" + (new Date().getTime() - startTime));
long endTime = new Date().getTime();
list.parallelStream().forEach(f -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("并行所用时间" + (new Date().getTime() - endTime));
}
}
class Student {
private Integer id;
private String name;
private Integer age;
public Student() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}