Iteration can be replaced with bulk 'Collection.addAll'

G. Dawid :

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.

Federico Peralta Schaffner :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110795&siteId=1