Using Java, How to Compare Every Entry in Hashmap to Every Other Entry in the Same Hashmap Without Duplicating Comparisons

Using Java, how can I compare every entry in HashMap to every other entry in the same HashMap without duplicating comparisons?

If you are not careful, the cost of eliminating duplicates could higher than the cost of redundant comparisons for the keys at least.

You can order the keys using System.identityHashCode(x)

for(Map.Entry<Key, Value> entry1: map.entrySet()) {
Key key1 = entry1.getKey();
int hash1 = System.identityHashCode(key1);
Value value1 = entry1.getValue();
for(Map.Entry<Key, Value> entry2: map.entrySet()) {
Key key2 = entry2.getKey();
if (key1 > System.identityHashCode(key2)) continue;

Value value2 = entry1.getValue();
// compare value1 and value2;
}
}

I want to compare the each value in a java map with another value

You grouping by the map value and collect those entry with same value into a Map.

Map<Double, Map<String, Double>> result = 
map.entrySet().stream()
.collect(groupingBy(Entry::getValue, toMap(Entry::getKey, Entry::getValue)));

This will give you result like:

{
123.12345 -> {
First -> 123.12345,
Fourth -> 123.12345
},
234.3456 -> ...
}

In java 7:

Map<Double, Map<String, Double>> result = new HashMap<>();
for (Entry<String, Double> mapping : map.entrySet()) {
Double value = mapping.getValue();
if (!result.containsKey(value)) {
result.put(value, new HashMap<>());
}
// Add new pair to map
result.get(value).put(mapping.getKey(), value);
}

how to compare two hashmaps and display true for the same values?

You don't need 2 separate loop. Iterate over the first map, and get the value for that key from the other map too, and compare them.

Sample code:

Map<Integer, String> firstMap = new HashMap<Integer, String>();
Map<Integer, String> secondMap = new HashMap<Integer, String>();

for (Entry<Integer, String> firstEntry : firstMap.entrySet()) {
String firstMapValue = firstEntry.getValue();
String secondMapValue = secondMap.get(firstEntry.getKey());
System.out.println(firstEntry.getKey() + " " + firstMapValue + " " + secondMapValue + " " + firstMapValue.equals(secondMapValue));
}

Compare hashMap values

Check each letter in your ransom note and see if there are enough in the newspaper:

boolean enoughLetters(Map<Character, Integer> magMap, Map<Character,Integer> ransomMap) {
for( Entry<Character, Integer> e : ransomMap.entrySet() ) {
Character letter = e.getKey();
Integer available = magMap.get(letter);
if (available == null || e.getValue() > available) return false;
}
return true;
}


Related Topics



Leave a reply



Submit