Reputation: 897
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:
The types for the map is:
private final Map<Integer, Friend> mapInvitedFriends = new HashMap<>();
private final List<Friend> listFriends = new ArrayList<>();
Upvotes: 1
Views: 180
Reputation: 393986
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);
Upvotes: 4