How to count duplicate values in HashMap in Java

What you will learn here about java

  • How to count duplicate values in HashMap in Java

In java it is very easy to find count of duplicate values in java. Here we will see how to count duplicate values in hashMap using Stream Api.

How to count duplicate values in HashMap in Java

The sample program for counting duplicate values in hashMap is given below.

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharOccurrenceCount {
    public static void main(String[] args) {
        HashMap<Integer, String> hashMap=new HashMap<>();
        hashMap.put(01,"Google");
        hashMap.put(02,"TCS");
        hashMap.put(03,"Apple");
        hashMap.put(04,"Google");
        hashMap.put(05,"Apple");
        hashMap.put(06,"Microsoft");

        Map<String, Long>values=hashMap.values().stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
        System.out.println("Values Count : "+values);
    }
}

OUTPUT

Values Count : {Google=2, Apple=2, TCS=1, Microsoft=1}

You may also like...