You’ll often find yourself needing to check if all values in a Map are equal — for example, when validating user preferences or verifying data consistency in your application.
In this guide, you’ll discover seven different ways to tackle this common programming challenge, from Stream API solutions to traditional loop approaches.
Whether you’re working with HashMap, TreeMap, or any other Map implementation, you’ll learn the most efficient methods to verify value equality, complete with practical code examples that you can start using in your projects today.
1. Java 8 Stream distinct()
distinct()
returns a stream with distinct(unique) elements from the source stream.
If the size of that stream is 1, means all elements were the same.
public boolean areAllValuesEqual(Map map) { if (map == null || map.isEmpty()) { return true; } return map. values(). stream(). distinct(). count() == 1; }
2. Java 8 Stream allMatch()
If you prefer more explicit control, you can use the allMatch()
approach.
allMatch()
will return true
if all the values of stream match the provided predicate, where we are comparing the current value with the first element.
public boolean areAllValuesEqualWithAllMatch(Map map) { if (map == null || map.isEmpty()) { return true; } Object firstValue = map. values(). iterator(). next(); return map. values(). stream(). allMatch(value -> Objects.equals(value, firstValue)); }
3. Looping
Get the first value from the map.
Then iterate over the map and compare the first value with all the other values.
Below is the code example
public boolean areAllValuesEqual(Map map) { if (map == null || map.isEmpty()) { return true; } Object firstValue = map. values(). iterator(). next(); for (Object value : map.values()) { if (!value.equals(firstValue)) { return false; } } return true; }
With this approach, you get complete control over the comparison process, and you can easily add custom logic or debugging.
4. Using HashSet
Convert all the map’s values into a HashSet
using its constructor.
Since a HashSet only stores unique elements, if all values are equal, you’ll end up with a set of size 1.
Here’s how you can implement this:
public boolean areAllValuesEqual(Map<String, Integer> map) { if (map == null || map.isEmpty()) { return true; } return new HashSet<>(map.values()).size() == 1; }
5. Using Collections.frequency()
Another approach you can use involves the Collections.frequency()
method.
This technique counts how many times your first value appears in the entire collection of values.
If it matches the size of your map, means— all values are equal!
public boolean checkValuesEqualityWithFrequency(Map<String, Integer> map) { if (map == null || map.isEmpty()) { return true; } Collection values = map.values(); Integer firstValue = values.iterator().next(); return Collections.frequency(values, firstValue) == values.size(); }
What’s fantastic about these collection-based methods is their simplicity.
You don’t need to wrap your head around complex stream operations, and they’re often more intuitive when you’re reviewing code later.
Plus, if you’re working with smaller maps, they can be quite efficient!
6. Apache Commons Collections
Unlike the built-in Java methods you’ve seen earlier, third-party libraries can offer more elegant and concise solutions for checking map value equality.
Let’s start with Apache Commons Collections, which provides a neat one-liner solution using IterableUtils
:
import org.apache.commons.collections4.IterableUtils; Map<String, Integer> scores = Map.of( "X", 95, "Y", 95, "Z", 95 ); boolean areEqual = IterableUtils. frequency(scores.values(), scores. values(). iterator(). next()) == scores.size();
IterableUtils.frequency()
counts the number of occurrences of the specified object(given as second argument )in the given collection(gives as first argument).
If the frequency of occurrence is equal to the size of the collection, then it means that all the elements are same.
7. Using Google Guava
You can also leverage Google guava’s Sets
class to determine if all values of map are same as shown below
import com.google.common.collect.Sets; Map<String, String> preferences = Map.of( "theme", "dark", "language", "dark", "mode", "dark" ); boolean areEqual = Sets.newHashSet(preferences.values()).size() == 1;
newHashSet()
method creates a new set with unique values, out of the argument values
We provide the values of map to this method and then compare its size.
If it is 1, means that all the values were same.
Testing and Validation
To ensure your map value comparison logic works flawlessly, you’ll want to set up comprehensive test cases.
Here’s a practical JUnit test class that you can use as a starting point for your testing journey:
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class MapValueComparatorTest { @Test void testAllValuesEqual() { Map<String, Integer> map = new HashMap<>(); map.put("a", 42); map.put("b", 42); map.put("c", 42); assertTrue(areAllValuesEqual(map)); } @Test void testDifferentValues() { Map<String, Integer> map = new HashMap<>(); map.put("a", 42); map.put("b", 43); map.put("c", 42); assertFalse(areAllValuesEqual(map)); } @Test void testEmptyMap() { Map<String, Integer> map = new HashMap<>(); assertTrue(areAllValuesEqual(map)); } @Test void testNullValues() { Map<String, Integer> map = new HashMap<>(); map.put("a", null); map.put("b", null); assertTrue(areAllValuesEqual(map)); } }
You’ll want to test various scenarios in your map comparisons.
Think about those tricky edge cases —
what happens with an empty map?
How about when you’ve got null values mixed in?
Your tests should cover all these scenarios to keep your code rock-solid.
Here’s a handy test data generator you can use to create larger test cases:
private Map<String, Integer> generateTestMap(int size, boolean allEqual) { Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < size; i++) { map.put("key" + i, allEqual ? 42 : (i % 2 == 0 ? 42 : 43)); } return map; }
When you’re testing performance, you might want to add some benchmarking tests. Here’s a simple way to measure execution time:
@Test void performanceBenchmark() { Map<String, Integer> largeMap = generateTestMap(10000, true); long start = System.nanoTime(); boolean result = areAllValuesEqual(largeMap); long end = System.nanoTime(); System.out.printf("Execution time: %d ms%n", (end - start) / 1000000); assertTrue(result); }
By running these tests, you’ll feel confident about how your implementation performs with different data sizes and patterns.
Don’t forget to test your code with both small and large maps — sometimes issues only show up when you’re dealing with bigger datasets!
Summing up
You now have a variety of approaches for checking map value equality in Java!
From the Stream API approach to the straightforward HashSet method, you can pick what works best for your specific needs.