版权声明:ssupdding https://blog.csdn.net/sspudding/article/details/88633750
统计100000个数据出现的次数和第一个重复出现的数字
100000个数据在1—1000范围之内
public class Demo3 {
public static void main(String[] args) {
//将数据存入ArrayList中
ArrayList<Integer> arrayList = new ArrayList<>();
Random random = new Random();
//产生100000个数据
for (int i = 0; i < 100000; i++) {
arrayList.add(random.nextInt(1000)+1); //用随机数产生1-1000的数据
}
//统计数据出现的次数
HashMap<Integer,Integer> hashMap = new HashMap<>(); //key存储1-1000的数字,value存放出现的次数
Iterator<Integer> it = arrayList.iterator();
while (it.hasNext()){
Integer key = it.next();
if (hashMap.containsKey(key)){//如果key已经存在
hashMap.put(key,hashMap.get(key)+1);
}else {//key不存在
hashMap.put(key,1);
}
}
Iterator<Map.Entry<Integer,Integer>> it1 = hashMap.entrySet().iterator();
while (it1.hasNext()){
Map.Entry<Integer,Integer> next = it1.next();
Integer key = next.getKey();
Integer value = next.getValue();
System.out.println(key+":"+value);
}
//找第一个重复的数据
HashMap<Integer,Integer> hashMap1 = new HashMap<>();
Iterator<Integer> it2 = arrayList.iterator();
while (it2.hasNext()) {
Integer key = it2.next();
if (hashMap1.containsKey(key)) {
hashMap1.put(key,hashMap1.get(key)+1);
System.out.println("第一个重复的数据为:" + key);
break;
} else {
hashMap1.put(key, 1);
}
}
//打印全部数据
System.out.print(arrayList);
}
}
部分结果: