Core Java

Check If Map Values Are All The Same

In Java, Maps are commonly used to store key-value pairs, where each key is unique, but multiple keys can have the same value. Sometimes, we need to check if all the values in a map are identical. This can be useful in scenarios where consistency across map values is required. Let us delve into understanding the various methods to check if all values in a map are the same in Java.

1. Checking if All Values in a Map Are the Same

We can check if all values in a map are the same using several approaches in Java.

1.1 Using Java 8 Stream API

The Stream API introduced in Java 8 makes it easy to process collections of data, including maps. We can use the allMatch() method of the Stream API to check if all values are the same.

package com.jcg.example; 

import java.util.HashMap;
import java.util.Map;

public class CheckMapValues {
    public static void main(String[] args) {
        // Creating a sample map
        Map<String, Integer> map = new HashMap<>();
        map.put("a", 10);
        map.put("b", 10);
        map.put("c", 10);

        // Using Stream API to check if all values are the same
        boolean allValuesSame = map.values().stream().allMatch(val -> val.equals(map.values().iterator().next()));
        
        // Output the result
        System.out.println("Are all values the same? " + allValuesSame);
    }
}

1.1.1 Code Explanation and Output

A map is created using the HashMap class, which stores key-value pairs. The map is defined to hold String keys and Integer values. The map is initialized with three key-value pairs, where each key (“a”, “b”, “c”) has the value 10. The map’s values() method returns a collection of all the values in the map. These values are converted to a stream using stream(). The allMatch() method is used to check if all values are the same. It compares each value to the first value in the map by using val.equals(map.values().iterator().next()). If all values are the same, it returns true, otherwise false. Finally, the result is printed using System.out.println(), which outputs whether all map values are the same or not.

The output of the code will be:

Are all values the same? True

1.2 Using Set to Compare Values

Another approach is to convert the map values into a set. Since a set only contains unique elements, if all map values are the same, the set will have only one element.

package com.jcg.example; 

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CheckMapValues {
    public static void main(String[] args) {
        // Creating a sample map
        Map<String, Integer> map = new HashMap<>();
        map.put("a", 10);
        map.put("b", 10);
        map.put("c", 10);

        // Convert map values to a set
        Set<Integer> valueSet = Set.copyOf(map.values());

        // If the set contains only one element, all values are the same
        boolean allValuesSame = valueSet.size() == 1;
        
        // Output the result
        System.out.println("Are all values the same? " + allValuesSame);
    }
}

1.2.1 Code Explanation and Output

A HashMap is created to store key-value pairs where the keys are of type String and the values are of type Integer. The map is initialized with three key-value pairs, each having the value 10. The values() method is called on the map, which returns a collection of all the values. The values are then converted to a Set using the Set.copyOf() method. A set only allows unique values, so if all values in the map are the same, the set will have only one element. The program checks if the set contains only one element using valueSet.size() == 1. If the set has only one element, it means all values in the map are identical. The result is printed to the console using System.out.println(), indicating whether all the map values are the same or not.

The output of this program will be:

Are all values the same? True

1.3 Using a Simple Loop

If you’re not using Java 8 or prefer a more straightforward approach, you can iterate through the map values manually and compare each value with the first one.

import java.util.HashMap;
import java.util.Map;

public class CheckMapValues {
    public static void main(String[] args) {
        // Creating a sample map
        Map map = new HashMap();
        map.put("a", 10);
        map.put("b", 10);
        map.put("c", 10);

        // Using a simple loop to check if all values are the same
        boolean allValuesSame = true;
        Integer firstValue = null;

        for (Integer value : map.values()) {
            if (firstValue == null) {
                firstValue = value;
            } else if (!value.equals(firstValue)) {
                allValuesSame = false;
                break;
            }
        }

        // Output the result
        System.out.println("Are all values the same? " + allValuesSame);
    }
}

1.3.1 Code Explanation and Output

A HashMap is created to store key-value pairs where the keys are of type String and the values are of type Integer. The map is initialized with three key-value pairs: (“a”, 10), (“b”, 10), and (“c”, 10). Two variables are initialized:

  • allValuesSame: A boolean variable set to true by default. This variable will indicate whether all map values are the same.
  • firstValue: An Integer variable initialized to null. It will store the value of the first element in the map during iteration.

The code then iterates over the values in the map using a for-each loop. On the first iteration, the value of the first map element is stored in the firstValue variable. For each subsequent iteration, it compares the current value with firstValue. If any value is different from firstValue, the allValuesSame variable is set to false, and the loop is terminated with the break statement. After the loop completes, the program prints the result using System.out.println(), displaying whether all map values are the same or not.

The output of this program will be:

Are all values the same? True

2. Performance Comparison

Let’s now compare the performance of the three methods using a simple table. We consider time complexity and memory usage for each approach:

MethodTime ComplexityMemory UsageAdvantagesDisadvantages
Using Stream APIO(n) – Iterates over all values onceO(n) – Requires space for the streamConcise and readable codeStream operations may be slightly slower due to overhead
Using SetO(n) – Converts values to a set and checks sizeO(n) – Requires extra space for the setSimple and effectiveRequires additional space for storing unique values
Using a Simple LoopO(n) – Iterates over all values onceO(1) – No extra space neededOptimal in terms of memory usageCode may be less readable for large maps

3. Conclusion

Checking if all values in a map are the same is a common requirement in many Java applications. Using the techniques described above, you can easily achieve this by leveraging Java 8’s Stream API, converting values to a set, or using a simple loop. Each of these methods has its pros and cons. The Stream API is concise and modern but may incur overhead. The Set-based method is simple but requires extra memory, while the loop method is the most memory-efficient but can be less readable.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button