I am comparing 2 maps using Java 8 features and based on condition wants to return the result. Using .forEach is showing compile time error and basically, the return is returning from Lambda expression and not from the loop. How can I return from the loop enclosing the lambda?
Note that I am not comparing for equality for the two map objects
nMap.forEach((k,v) -> {
if (!mMap.containsKey(k) || mMap.get(k) < v) {
return -1;
}
});
We can check if two HashMap objects have the same keys by comparing their keys obtained using the keySet() method. We use equals() method of the set to compare keys.
HashMap uses equals() to compare the key to whether they are equal or not. If the equals() method return true, they are equal otherwise not equal. A single bucket can have more than one node, it depends on the hashCode() method. The better your hashCode() method is, the better your buckets will be utilized.
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.
@paweloque For Comparing two Map Objects in java, you can add the keys of a map to list and with those 2 lists you can use the methods retainAll() and removeAll() and add them to another common keys list and different keys list. Using the keys of the common list and different list you can iterate through map, using equals you can compare the maps.
Some examples of Map in Java 8 is to convert a list of integers and then the square of each number. The map function is also an intermediate operation and it returns a stream of the transformed element.
Map.merge () Java 8 adds a new merge () function into the java.util.Map interface. Here is how the merge () function works: If the specified key is not already associated with a value or the value is null, it associates the key with the given value. Otherwise, it replaces the value with the results of the given remapping function.
Java 8 Streams provide Collectors.toMap (keyMapper, valueMapper, mergeFunction, mapFactory) overloaded method where you can specify the type using mapFactory to return ConcurrentHashMap, LinkedHashMap or TreeMap. A Map is returned, when you group a stream of objects using Collectors.groupingBy (keyMapper, valueMapper).
Use a Stream
of the entrySet()
and anyMatch
instead of forEach
:
boolean found =
nMap.entrySet()
.stream()
.anyMatch(e -> !mMap.containsKey(e.getKey()) || mMap.get(e.getKey()) < e.getValue());
if (found)
return -1;
Another approach using a Stream
which filters the entries according to the given condition. The result of the streaming is an Optional
which may contain a found Entry
:
if (nMap.entrySet().stream()
.filter(e -> !mMap.containsKey(e.getKey()) || mMap.get(e.getKey()) < e.getValue())
.findAny()
.isPresent()) {
return -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With