Reputation: 12471
I have a method that contains a lambda
expression:
public int noOfComplementaryPairs1(int arr[], int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
map.merge(k - arr[i], 1, Integer::sum);
}
return Arrays.stream(arr).map(element -> map.getOrDefault(element, 0)).sum();
}
Can someone explain to me what the last 2 lines mean? I am not new to Java, but sometimes I get confused with some expressions like this one.
Upvotes: 2
Views: 98
Reputation: 121068
map.merge...
: the first param is the key in the map, the second param is the value in the map when this key is not present, the third one is a BiFunction
that tells u how to merge two keys, since u cant have two keys with the same value inside a Map..
The last line is pretty simple too: you are streaming the array, mapping each element of that array with: map.getOrDefault(element, 0)
, which means get the value from the map
with key = element
or the default of zero if it is not present; then sum
them all.
Upvotes: 3