2

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.

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How about the lambda expression? It will be helpful to upvote the question btw
How about using Map<Integer, Integer> map = IntStream.range(0, arr.length).boxed().collect(Collectors.toMap(i -> k - arr[i], i -> 1, Integer::sum)); instead of the for loop? Any pros or cons you might want to add to the answer.
@nullpointer hardly do I agree here, way less readable; but ultimately it's the OP to decide

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.