Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Value for map.compute is always null

I’m trying to use .compute() on my map but the else statement is never fired.

public void onInviteUser(int adapterPosition) {
        Log.d(TAG, "onInviteUser: " + adapterPosition); //not null
        mapInvitedFriends.compute(adapterPosition, (k, v) -> {
            Log.d(TAG, "onInviteUser: " + adapterPosition); 
            if (v == null) {
                Log.d(TAG, "onInviteUser: " + v);
                mapInvitedFriends.put(adapterPosition, listFriends.get(adapterPosition));
                Log.d(TAG, "onInviteUser: " + listFriends.get(adapterPosition).toString());
                return v;
            } else {
                //Never gets fired
                Log.d(TAG, "onInviteUser: " + v);
                mapInvitedFriends.remove(adapterPosition);
                return v;
            }
        });
}

I’ve logged everthing, but I can’t figure out why the value v is always null.

Edit:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The types for the map is:

private final Map<Integer, Friend> mapInvitedFriends = new HashMap<>();
private final List<Friend> listFriends = new ArrayList<>();

>Solution :

You are not use compute correctly:

The remapping function should not modify this map during computation.

Therefore you shouldn’t call to mapInvitedFriends.put or mapInvitedFriends.remove inside the function.

Instead, you can try:

    mapInvitedFriends.compute(adapterPosition, (k, v) -> {
        Log.d(TAG, "onInviteUser: " + adapterPosition); 
        if (v == null) {
            return listFriends.get(adapterPosition); // this will cause a new mapping to be added
        } else {
            return null; // this will cause the existing mapping to be removed
        }
    });

or simply:

mapInvitedFriends.compute(adapterPosition,
                          (k, v) -> v == null ? listFriends.get(adapterPosition) : null);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading