Iteration can be replaced with bulk 'Collection.addAll'

  • A+

So my goal is to fill arraty with y random numbers from 1 to x section, and then count how many times each number is duplicated and print it. Here is code:

int counter = 1;     int length = random.length;     Map<Integer, Integer> hashMap = new HashMap<>();     for(int i = 0; i < length - 1; i++)     {         if(random[i] == random[i+1])         {             counter++;         }         else         {             hashMap.put(random[i], counter);             System.out.println(random[i] + " duplicate : " + counter + " times.");             counter = 1;         }     } 

And my problem is at if statment, it wont show how many times last number is buplicated, coz it will add one to counter and won't save it. How could I fix it? If you have ideas overall, how could I do this better way, then using for+if with array, go ahead and give me hint. Thanks for help in advance.


With Java8+, you can use Map.merge:

Map<Integer, Integer> hashMap = new HashMap<>(); for (int n : random) {     hashMap.merge(n, 1, Integer::sum); } 

Which reads as follows: for every number n in the random array, put it in the map with value 1, and if it's already present, sum 1 to its value.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: