-3

What's the recommended approach for comparing hashmaps in Java for equality so that I can determine if they have identical keys and values?

Map<String,List<String>> data1 = new HashMap<>();
data1.put("file1", Arrays.asList("one","two","three"));

Map<String,List<String>> data2 = new HashMap<>();
data2.put("file1", Arrays.asList("one","two","three"));
A_B
  • 1,009
  • 3
  • 15
  • 37
  • 2
    [`Map.equals()`](https://docs.oracle.com/javase/8/docs/api/java/util/AbstractMap.html#equals-java.lang.Object-) – Sharon Ben Asher Aug 13 '19 at 20:24
  • 3
    Simply `data1.equals(data2)` – Jacob G. Aug 13 '19 at 20:24
  • The question may have some other considerations, like: what is more efficient (faster)? If the keys are identical, does it mean the values are implied? more docs: https://howtodoinjava.com/java/collections/hashmap/compare-two-hashmaps/ – azbarcea Aug 13 '19 at 20:28

2 Answers2

0

By default, HashMap.equals() method compares two hashmaps by key-value pairs. It means both hashmap instances must have exactly same key-value pairs and both must be of same size.

Valdrinium
  • 1,398
  • 1
  • 13
  • 28
0

Just use equals method.

boolean equals = data1.equals(data2);
nishantc1527
  • 376
  • 1
  • 12