Lightcaster5 :
Let's say I have a HashMap<String, Integer>
containing usernames and their position as an int in a queue or line. How would I go about removing a user from the queue and subsequently update all the values for the users behind?
Arvind Kumar Avinash :
You can do it as follows:
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
static Map<String, Integer> queueMap = new LinkedHashMap<String, Integer>();
public static void main(String[] args) {
queueMap.put("Arvind", 5);
queueMap.put("Avinash", 6);
queueMap.put("Kumar", 7);
queueMap.put("Lightcaster", 8);
queueMap.put("Stackoverflow", 9);
System.out.println("Before: " + queueMap);
removeFromQueue("Kumar");
System.out.println("After: " + queueMap);
}
static void removeFromQueue(String user) {
final Integer userPlace = queueMap.get(user);
if (userPlace != null) {
queueMap.replaceAll((k, v) -> v > userPlace ? v - 1 : v);
queueMap.remove(user);
}
}
}
Output:
Before: {Arvind=5, Avinash=6, Kumar=7, Lightcaster=8, Stackoverflow=9}
After: {Arvind=5, Avinash=6, Lightcaster=7, Stackoverflow=8}